The Async Keyword
Just as the await keyword replaces the need for .then(), the async keyword replaces the need to manually write new Promise().
When you prefix a function declaration with the async keyword, two very important things happen:
- It allows you to use the
awaitkeyword inside the function. (You cannot useawaitinside a normal, synchronous function). - It automatically wraps the function’s return value in a Promise.
new Promise() vs async
Here is an older approach creating a Promise manually:
function getPromiseForUserData() {
return new Promise((resolve) => {
fetchDataFromServer().then(function(user) {
resolve(user);
});
});
}
And here is the exact same logic using async/await:
async function getPromiseForUserData() {
const user = await fetchDataFromServer();
return user; // This is automatically wrapped in a Promise!
}
// When called, both functions return a Promise object
const myPromise = getPromiseForUserData();
Because an async function always returns a Promise, any code that calls your async function must be prepared to await it (or use .then()).