In previous post, we have talked about Promise https://frontend.cloudaccess.host/callback-in-javascript/. There is no doubt that Promise offers more readability compare to callback, but there is still a lot of boiler code. For that reason, this post will show you a way to make Promise even more readability

What is await and async in Javascript

await and async in javascript is just a syntax for ES6, that make our asynchronous task look like synchronous. Await and async cannot replace Promise, we still need to use Promise to handle asynchronous tasks. Nevertheless, It gives us an easier way to deal with Promise.

Traditionally, with Promise, when we want to catch the value which is returned by asynchronous task, we need to call method `then` and put the callback function inside this. With await and async, we have an alternative way to catch up that value.

How to use Async and Await

To use Await & Async, we need to do 2 steps

  • Firstly, replacing promise.then(callback) by await to make code look like synchronous way.
  • Secondly, we also need to put async for the method which has await process.


var promise = new Promise(function(resolver, reject) {
  setTimeout(function() {
    resolver("finished");
  }, 2000);
});
//Promise way
promise.then(function(value){
   console.log(`Promise value is ${value}`)
})
//Async way
async function getValue(){
    var value = await promise;
   console.log(`Promise value is ${value}`)
}
getValue()

Put in practice

See the Pen Async by hieu (@phuchieuct93abc) on CodePen.

In short

The combination between Promise and Await & Async help us to handle asynchronous tasks that look like synchrous

Leave a Reply

Your email address will not be published.