In this JavaScript lesson we are going to learn about JavaScript Async & Await, ES8 came up with async and await keywords which can be used for asynchronous functionality in JavaScript. when an async function is called, it returns a Promise, when the async function returns a value, the Promise will be resolved with the returned value. When the async function throws an exception , the Promise will be rejected with the thrown value. It is important to mention that async function works on top of promises. they use promises to return the results. and also you need to remember that async function and await works together. you can use await only inside async function. using it outside will throw an error. and await allows you to pause execution of async function and wait until promise is resolved, either as fulfilled or rejected.
1 2 3 4 5 6 7 |
async function functionName() { //function body let asyncResult = await ourAsyncFunction(); return asyncResult; } |
Multiple await
1 2 3 4 5 6 7 8 |
async function functionName() { //function body let asyncResult = await ourAsyncFunction(); let asyncResult2 = await ourSecondAsyncFunction(); return asyncResult + asyncResult2; } |
Once all await are resolved in an async function, it will be considered as completed. the first async function may have a promise or could be using a promise object and the rest will simply await till the previous one is resolved. see the example below of a promise chain.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
function mypromise() { return new Promise(resolve => { setTimeout(() => { resolve('Promise is resolved') }, 3000); }); } async function ourMsg() { const message = await mypromise(); //please wait untile this promise //has been resolved or rejected console.log(`Message : ${message}`); } ourMsg(); |
now in here using await we are going to tell that wait for a promise to resolve or reject. It can only be used inside an async function.
When you have multiple steps you will see the power of async or await.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
function FirstPromise() { return new Promise(resolve => { setTimeout(() => { resolve('First Promise Resolved'); }, 200); }); } function SecondPromise() { return new Promise(resolve => { setTimeout(() => { resolve('Second Promise Resolved'); }, 300); }); } function ThirdPromise() { return new Promise(resolve => { setTimeout(() => { resolve('Third Promise Resolved'); }, 5000); }); } async function message() { //const first = await FirstPromise(); //const second = await SecondPromise(); //const third = await ThirdPromise(); const [first, second, third] = await Promise.all([FirstPromise(), SecondPromise(), ThirdPromise()]); console.log( `${first} ${second} ${third}`); } message(); |
Practical example
1 2 3 4 5 6 7 8 9 |
async function getUser(name) { let response = await fetch(`https://api.github.com/users/${name}`); let data = await response.json() return data; } getUser('Parwiz') .then(data => console.log(data)) |