async
andawait
are syntactic sugar for working with Promises.async function
is syntactically closer toreturn new Promise(...)
statement.await
operator is analogous toPromise.then
method.- Together they help write asynchronous code without nested callbacks or then blocks.
async
keyword/modifier wraps a function in aPromise
.- It returns a
Promise
, instead of the expression in the function'sreturn
statement. - This promise may
resolve
with the value of the expression in the return statement. - Or it may
reject
with the reason of error encountered during the function execution.
await
operator unwraps aPromise
.- It extracts the
resolve
d value if the promise isfulfilled
. - Or it throws with
reject
ed reason if the promise isrejected
.
- An
async
function always returns a promise andawait
can access its return value. async
functions run synchronously till anawait
operation is encountered.await
operation defers execution ofasync
functions, lettingpending
promises getsettled
.- So an
async
function with noawait
statements ends synchronously. - And an
async
function withawait
statements ends asynchronously. await
can only be used inside anasync
function, at least for now.
async
andawait
offer no alternative to working with Promises for handling multipleasync
functions or promises.Promise
methodsall
,allSettled
,any
andrace
are required toawait
multipleasync
functions or promises.