JAVASCRIPT / CHAPTER 13

Promises and failure paths

Advanced

Reason 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.

JavaScript example
console.log("start");
Promise.resolve("ready").then(value => console.log(value));
console.log("end");
Result
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 challenges

CHECK YOUR UNDERSTANDING

Chapter checkpoint

Every result is required, and any rejection should reject the combined operation. Which API matches?