Comparison between Promises and AsyncAwait
suggest changeFunction using promises:
function myAsyncFunction() {
return aFunctionThatReturnsAPromise()
// doSomething is a sync function
.then(result => doSomething(result))
.catch(handleError);
}
The same control flow with async/await:
async function myAsyncFunction() {
try {
const result = await aFunctionThatReturnsAPromise();
// doSomething is a sync function
return doSomething(result);
} catch (error) {
return handleError(error);
}
}
An async function always returns a promise, similar to wrapping the body in return new Promise((resolve, reject) => { ... }).
await reads the fulfillment value the way a then callback does.
This short gif shows the same comparison:
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents