JAVASCRIPT / CHAPTER 14

Concurrent promises and result ordering

Advanced

Distinguish starting work from awaiting its completion.

By the end of this chapter

  • Start independent operations before awaiting
  • Preserve input order in combined results
  • Choose fail-fast or settled-result handling

The idea

Await pauses an async function’s continuation until its operand settles; it does not stop all other JavaScript work. Two independent operations can be started before either is awaited. Promise.all combines them and returns values in input order, even if they finish in another order. By contrast, awaiting one operation before starting the second expresses a dependency and usually loses concurrency.

Choose failure behavior according to the application contract. Promise.all rejects when an input rejects, but this does not automatically cancel the other operations. Promise.allSettled waits for every outcome and reports each as fulfilled or rejected. A tolerant report can use those individual outcomes, while a calculation requiring every input should surface failure. Avoid async callbacks in forEach when the caller needs a promise representing completion of all work.

JavaScript example
async function report() {
  const tasks = [Promise.resolve("first"), Promise.resolve("second")];
  const values = await Promise.all(tasks);
  console.log(values.join("/"));
}
report();
Result
first/second

The combined array follows the tasks array order, not a completion race.

Try it yourself

Build a report from independent requests that retains successful results and explicitly lists failures.

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

Which operation reports both successful and failed outcomes after all supplied promises settle?