JS Async Function

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 asyncfunction throws an exception or some value, the Promise will be rejected with the thrown value.

function workAfter2Seconds(x) { return new Promise(resolve => { setTimeout(() => { resolve(x); }, 2000); }); } async function add1(x) { const a = await workAfter2Seconds(20); const b = await workAfter2Seconds(30); return x + a + b; } add1(10).then(v => { console.log(v); // prints 60 after 4 seconds. }); async function add2(x) { const p_a = workAfter2Seconds(20); const p_b = workAfter2Seconds(30); return x + await p_a + await p_b; } add2(10).then(v => { console.log(v); // prints 60 after 2 seconds. });