Saturday, March 30, 2024

Explain Javascript Async/Await?

"async and await make promises easier to write". async makes a function return a Promise while await makes a function wait for a Promise

Async Syntax:

The keyword async before a function makes the function return a promise:

Example:

async function myFunction() {

  return "Hello";

}

The above is the same as below:

function myFunction() {

  return Promise.resolve("Hello");

}

Await Syntax:

The await keyword can only be used inside an async function.

The await keyword makes the function pause the execution and wait for a resolved promise before it continues:

let value = await promise;

Let us understand this with an example,

function myFunction(some) {

  console.log('Inside myFunction');

}

async function promiseDemonstration(){

let myPromise = new Promise(function(myResolve, myReject) {

   let x = 0;

  if (x == 0) {

    myResolve("OK");

    console.log('Inside If');

    setTimeout(myFunction , 3000);

  } else {

    console.log('Inside else');

    myReject("Error");

  }

});

let value = await myPromise;

console.log('Awaiting Promise'+value);

myPromise.then(

  function(value) {

    console.log('Inside Value');

    myFunction(value);},

  function(error) {

    console.log('Inside Error');

    myFunction(error);}

);

}

promiseDemonstration();

No comments:

Post a Comment