Promises and async functions
See where an async function pauses and why surrounding JavaScript can continue.
Represent a future result
A promise represents an operation that can fulfill with a value or reject with an error. An async function returns a promise even when its body returns an ordinary value.
How it works
Think of a Promise as a result with three possible states: pending, fulfilled, or rejected. await pauses the current async function until the result settles. Other work can continue while it waits. If the result rejects, follow the error path rather than trying to display it as data.
Trace code around await
Code in the async function runs up to its first await. The continuation runs later, even when the awaited promise is already fulfilled. The code that called the function can keep running while that continuation is pending. Use try and catch around awaited operations whose rejections you can handle.
Code example
async function showStatus() {
console.log("Requesting");
const status = await Promise.resolve("Ready");
console.log(status);
}
showStatus();
console.log("Caller continues");Check your understanding
Predict the order of the three log lines in the example.
See the example and explanation
- Example 1
- Given
Run showStatus() and the synchronous line that follows it. - Answer
Requesting Caller continues Ready
The initial call prints Requesting. The continuation is deferred at await, so the caller prints next. The awaited result prints last.