Async and Await in JavaScript
Quick Overview:
- The async keyword gives a simpler way to work with asynchronous promise-based code.
- Adding async at the start of a function makes it an async function.
- Inside an async function, use the await keyword before a call to a function that returns a promise. This makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.
- async and await enable to write code that uses asynchronous functions but looks like synchronous code.
- The async and await keywords make it easier to build an operation from a series of consecutive asynchronous function calls, avoiding the need to create explicit promise chains.
async function customAsyncFn() { await setTimeout(() => { console.log("called setTimeout"); }, Math.random() * 1000); console.log("exit fn customAsyncFn"); } //setTimeout is an async function but it will not returns a promise, //hence await will not wait at that point... //so first "exit fn customAsyncFn" will be printed customAsyncFn(); async function customAsyncFn2() { //make this async funtion to satisfy point 3 //Inside an async function, use the await keyword before a call to a function //that returns a promise. await new Promise(resolve => { setTimeout(() => { console.log("called setTimeout2"); resolve(); }, Math.random() * 1000); }); console.log("exit fn customAsyncFn2"); } //now in case of fn customAsyncFn2 //await will wait at that point until the promise is settled or rejected ////so first "called setTimeout2" will be printed customAsyncFn2();Output
exit fn customAsyncFn
called setTimeout
called setTimeout2
exit fn customAsyncFn2
called setTimeout
called setTimeout2
exit fn customAsyncFn2