‘async/await’ in JavaScript : easy breakdown
I had hard times learning async & await concept in JavaScript thats why I want to explain here as simply as i can so you won’t find it difficult at all:
For the async functions I presume you already know about Promises in JS, If not Please read about promise in JavaScript here:
async functions :
A function can be made async by using ‘async’ keyword. It can contain zero or more ‘await’ expression.
It works with Promise to avoid multiple .then() situation in promise chain or to write promise-based behaviour in a clear style manner.
Declaration : It can be declared using ‘async function’ where ‘await’ keyword is permitted within the function body.
await expression suspends the execution until the return promise is fulfilled or rejected thus making promise function behave as synchronously.
await is only valid inside the async function.
Example using Promise:
function resolveAfter6Second() {
console.log("starting a slow promise");
return new Promise ((resolve) => {
setTimeout( function () {
resolve("slow");
console.log("This is slow promise");
}, 6000);
} );
}
function resolveAfter3Second() {
console.log("starting fast promise");
return new Promise((resolve) => {
setTimeout(() => {
resolve("fast");
console.log("fast promise is done");
}, 3000);
});
}
async function sequentialStart() {
console.log("performing Sync Operation");
const slow = await resolveAfter6Second();
console.log(slow);
const fast = await resolveAfter3Second();
console.log(fast);
}
sequentialStart();