Async/Await combined with Promises
async and await are a second way of writing code that uses promises, not a replacement for them. An async function always returns a promise, and inside it await pauses the function until a promise settles, then hands back its value. The code reads from top to bottom like synchronous code, while the rest of the program keeps running during each pause.
The two styles mix freely, because both work with the same promise objects. Async/Await introduces the keywords; this page shows how they combine with the promise methods.
An async function returns a promise
Section titled “An async function returns a promise”Whatever an async function returns becomes the value of the promise it returns:
const getGreeting = async () => 'Hello';
const result = getGreeting();console.log(result);result.then((greeting) => console.log(greeting));This prints:
Promise { 'Hello' }HelloSo a caller that is not itself async uses then() to read the result, as on every other promise.
Awaiting a promise
Section titled “Awaiting a promise”The rest of the examples use a lookUpPrice() function, which returns a promise for a price and rejects for an unknown item. With await, adding up a basket looks like an ordinary loop:
const prices = { bread: 1.45, milk: 0.95, apples: 2.1 };
const lookUpPrice = (item) => new Promise((resolve, reject) => { setTimeout(() => { if (item in prices) { resolve(prices[item]); } else { reject(new Error(`No price for ${item}`)); } }, 50); });
const basketTotal = async (items) => { let total = 0; for (const item of items) { total += await lookUpPrice(item); } return total;};
basketTotal(['bread', 'milk', 'apples']).then((total) => console.log(`£${total.toFixed(2)}`));This prints:
£4.50Running awaited work in parallel
Section titled “Running awaited work in parallel”The loop above waits for each price before asking for the next, so three lookups take three times as long as one. When the steps do not depend on each other, start them all and await Promise.all() once:
const basketTotal = async (items) => { const itemPrices = await Promise.all(items.map(lookUpPrice)); return itemPrices.reduce((sum, price) => sum + price, 0);};
basketTotal(['bread', 'milk', 'apples']).then((total) => console.log(`£${total.toFixed(2)}`));This prints:
£4.50The result is the same, but the lookups now run at the same time. The other promise methods, such as Promise.allSettled() and Promise.any(), can be awaited in the same way.
Handling rejections with try…catch
Section titled “Handling rejections with try…catch”When an awaited promise is rejected, await throws its reason, so an ordinary try...catch handles it. A finally block runs either way, like the promise method finally():
const showPrice = async (item) => { try { const price = await lookUpPrice(item); console.log(`${item}: £${price.toFixed(2)}`); } catch (error) { console.log(error.message); } finally { console.log(`Finished looking up ${item}`); }};
showPrice('milk').then(() => showPrice('cheese'));This prints:
milk: £0.95Finished looking up milkNo price for cheeseFinished looking up cheeseChaining before awaiting
Section titled “Chaining before awaiting”await accepts any promise, including one built with then() and catch(). A short chain is often the neatest way to transform a value or supply a fallback without a whole try...catch block:
const priceLabel = async (item) => { const label = await lookUpPrice(item) .then((price) => `£${price.toFixed(2)}`) .catch(() => 'not sold here'); console.log(`${item}: ${label}`);};
priceLabel('bread').then(() => priceLabel('cheese'));This prints:
bread: £1.45cheese: not sold hereThe same pattern suits fetch(), as in const data = await fetch(url).then((response) => response.json()).
Pitfall: catching inside the helper
Section titled “Pitfall: catching inside the helper”If a helper function catches its own rejection and returns nothing, the caller’s await receives undefined instead of an error, and the caller cannot tell a failure from a missing value. Let rejections reach the caller and handle them there, unless the helper has a sensible fallback value to return.
In an ES module, await can also be used at the top level of the file, outside any function. In a classic script or a CommonJS file it is allowed only inside an async function.
Steve Griffith covers this topic in his video Combining Async Await with Promises.