JavaScript: async and await
An async function returns a Promise, and await pauses that function until another Promise settles.
What you will learn
- How to await a Promise inside an async function
- How to handle rejected work with try...catch
- How to avoid unnecessary sequential waits
Minimal example
async function loadItems() {
try {
const response = await fetch('/api/items');
if (!response.ok) throw new Error('Request failed');
return await response.json();
} catch (error) {
console.error(error);
return [];
}
}The function still returns a Promise. Callers can await it or attach then and catch.
Common mistakes
- Remember that
awaitis normally used inside an async function. - Check the HTTP response before parsing data; a network request can resolve even when the server returns an error status.
- Start independent Promises before awaiting them, or use
Promise.allwhen all results are needed.