In Promise
callback
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 whichhas 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
Await & Async