‘async/await’ in JavaScript : easy breakdown

Amitabh Mudgil
2 min readApr 9, 2023

--

async() => { await }

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:

https://amitabhiam.medium.com/i-promise-this-way-promise-won-t-break-your-heart-in-javascript-promises-727747b8a6ec

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();

--

--

Amitabh Mudgil
0 Followers

JavaScript Developer | Thoughts into Words through Medium