DEV Community

Ajay Baraiya
Ajay Baraiya

Posted on

Async and Await #JS mordern concept.

Async and Await enteres in to handle complexity of Promises.
Which is a call back of hell problem, to make it look like synchronous but it's act asynchronous and non-blocking behind the scenes.

const myFunction = () => { return 'Test'; } // Normal function
const myAsyncFunction = async () => {return 'Test'; } //Async function which will return a Promise now.
Enter fullscreen mode Exit fullscreen mode

As in above now we can create a Promise like function just by adding async in front of ().

We now want a function to wait till it's child function to finish it's execution.

Take a look at below example.

function FirstFunction(){
   setTimeout(function(){console.log('execution line we want to execute first and want to wait till 5 seconds.');}, 5000);
}

function SecondFunction(){
FirstFunction();
console.log('execution line we want to call last.');
}

function Start() {
      SecondFunction(); // Calling only second one as first called inside of it.
}

Start();// Calling start function

Output: 
"execution line we want to call last."

//Wait for 5 seconds to get below as we applied 5 seconds timeout.
"execution line we want to execute first and want to wait till 5 seconds."
Enter fullscreen mode Exit fullscreen mode

As in above example it will not wait till 5 seconds to complete.

Now to make it wait till 5 seconds, below is how we can achive using await.

const FirstFunction = async () => {
    return new Promise(resolve => {
    setTimeout(function(){return resolve('execution line we want to execute first and want to wait till 5 seconds.'); // Here creating promise is necessary and resolve in setTimeout to return resolve to make it synchronous
}, 5000);
  });
}

const SecondFunction = async () => { //remember we have to make it async so to use await in this function
const x = await FirstFunction(); // First function that is having async so it act like Promise here.
return x + '\nexecution line we want to call last.';
}

SecondFunction().then(res => {
  console.log(res)
});// Calling start function

Output: 
"execution line we want to execute first and want to wait till 5 seconds."
"execution line we want to call last."

Enter fullscreen mode Exit fullscreen mode

Top comments (0)