async / await
Writes promise-based code in a synchronous style using async/await.
async function fn() { const result = await promise; return result; }This static page keeps the syntax and examples indexed for search, while the coding app handles interactive exploration and saved references.
What it does
Overview
Writes promise-based code in a synchronous style using async/await.
The async and await keywords provide a powerful abstraction over Promises, allowing for asynchronous code that reads like synchronous logic. An async function inherently returns a Promise; if a non-promise value is returned, it is automatically wrapped in a resolved Promise. The await operator pauses the execution of the async function, yielding control back to the event loop until the Promise settles. This prevents blocking the main thread while waiting for I/O operations. Performance concerns include the 'async waterfall' anti-pattern, where independent operations are awaited sequentially rather than concurrently using Promise.all(). A critical edge case is the interaction with Array.prototype.forEach(), which does not wait for async callbacks because it is not designed to handle Promises. Note: Internet Explorer (IE) is not supported.
Quick reference
Syntax
async function fn() { const result = await promise; return result; }
See it in practice
Examples
Basic Asynchronous Data Fetching
async function fetchUser(id) {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/users/' + id);
const user = await response.json();
return user.name;
} catch (error) {
return 'User not found';
}
}// Returns a Promise that resolves to a string (e.g., "Leanne Graham")
Uses try/catch to handle network or parsing errors while awaiting sequential steps of an HTTP request.
Parallel Execution for Better Performance
async function getDashboard() {
const profilePromise = fetch('/api/profile');
const statsPromise = fetch('/api/stats');
const [profile, stats] = await Promise.all([
profilePromise.then(r => r.json()),
statsPromise.then(r => r.json())
]);
return { profile, stats };
}// Returns a Promise resolving to a combined object
Demonstrates avoiding a waterfall by initiating both requests before awaiting their results using Promise.all.
Sequential Iteration with for...of
async function processBatch(items) {
const results = [];
for (const item of items) {
const result = await someAsyncOperation(item);
results.push(result);
}
return results;
}// Returns a Promise resolving to an array of processed results
The for...of loop correctly handles awaiting each iteration, unlike forEach which would run all operations simultaneously without waiting.
Debug faster
Common Errors
LogicError
Cause: Forgetting the await keyword when calling an async function.
Fix: Ensure await is used to retrieve the resolved value, otherwise the variable will contain the Promise object itself.
const data = fetchData(); // Error: data is a Promise, not the resultLogicError
Cause: Using await inside a standard Array.prototype.forEach callback.
Fix: Use a for...of loop or Promise.all() with Array.prototype.map() to correctly handle asynchronous iterations.
items.forEach(async (item) => { await save(item); }); // Error: The loop finishes before the saves doPerformanceError
Cause: Creating an 'async waterfall' by awaiting independent promises one after another.
Fix: Start all independent promises first, then await them or use Promise.all to run them concurrently.
const a = await getA(); const b = await getB(); // b unnecessarily waits for aRuntime support
Compatibility
Source: MDN Web Docs
Common questions
Frequently Asked Questions
Writes promise-based code in a synchronous style using async/await.
LogicError: Ensure await is used to retrieve the resolved value, otherwise the variable will contain the Promise object itself. LogicError: Use a for...of loop or Promise.all() with Array.prototype.map() to correctly handle asynchronous iterations. PerformanceError: Start all independent promises first, then await them or use Promise.all to run them concurrently.