async function load() {
try {
const [user, posts] = await Promise.all([getUser(), getPosts()]);
return { user, posts };
} catch (err) {
console.error("load failed", err);
throw err;
}
}
An async function always returns a promise. Inside it, await pauses the function until a promise settles, then continues with the result.
- Returning a value from an
asyncfunction fulfills its promise. - Throwing inside it rejects its promise.
awaitresumes with the promise's value. If the promise rejects,awaitthrows the rejection reason on that line.
The rest of the program keeps running while the function waits. The engine schedules the resume as a microtask.
Error handling: rejections become thrown errors. So you handle them with normal try/catch/finally around the await. Another way is to call .catch() on the promise that the async function returns.
A promise that you do not await is not covered by the surrounding try.
A common performance mistake is awaiting independent work one after another. Each wait adds to the total time. Start them together and use await Promise.all([a(), b()]) so they run at the same time.
asyncfunctions always return a promise.awaitgives the promise's value, or throws its rejection.- Use
try/catcharoundawait, or.catch()on the returned promise. tryonly catches promises that youawait.- Use
Promise.allfor independent work instead of awaiting one after another.
Read more