JAVASCRIPT / CHAPTER 13
Promises and failure paths
AdvancedReason about asynchronous order and propagate failures.
By the end of this chapter
- Predict synchronous versus promise callback order
- Await returned work
- Choose all or allSettled for a stated failure policy
The idea
A promise represents a result that may become available later or fail. An async function always returns a promise. Await pauses that function until the awaited value settles; it does not block the whole program. Promise callbacks run after the current synchronous work has finished. Trace synchronous statements first, then the queued continuations, rather than assuming source order is execution order.
Compose work by returning or awaiting the promise you create. Otherwise callers cannot reliably wait for completion or catch its failure. Promise.all is appropriate when every result is required; one rejection rejects its combined promise. Promise.allSettled is useful when each outcome must be reported. Neither choice automatically cancels work already started, so cancellation and cleanup require their own design.
console.log("start");
Promise.resolve("ready").then(value => console.log(value));
console.log("end");start end ready
The current synchronous statements finish before the fulfilled promise callback executes. These snippets illustrate JavaScript semantics, not a particular editor runtime.
Try it yourself
Write an async function that awaits two supplied promise-returning operations and returns both results only if both succeed.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
Open JavaScript coding challengesCHECK YOUR UNDERSTANDING