🎓 A1Learner
🔍
0 of 50 lessons completed

JavaScript Async Patterns

Sequential awaits run one after another. Parallel awaits start together with Promise.all, and the order of the lines is the evidence.

Awaits in a row

The first await waits for its timer, then the second await waits for its own timer. The lines log in order, one after another.

function wait(value, ms) {
  return new Promise((resolve) => {
    setTimeout(() => resolve(value), ms);
  });
}
(async () => {
  const a = await wait("A", 50);
  console.log(a);
  const b = await wait("B", 50);
  console.log(b);
})();

Start together with Promise.all

Both timers start at the same time. Promise.all waits for both, then the log shows the results in list order.

function wait(value, ms) {
  return new Promise((resolve) => {
    setTimeout(() => resolve(value), ms);
  });
}
(async () => {
  const results = await Promise.all([wait("A", 50), wait("B", 50)]);
  console.log(results);
})();

Start first, await later

Both promises start before either await runs. The second timer finishes first, but the logs still follow the await order.

function wait(value, ms) {
  return new Promise((resolve) => {
    setTimeout(() => resolve(value), ms);
  });
}
(async () => {
  const p1 = wait("First", 50);
  const p2 = wait("Second", 30);
  console.log(await p1);
  console.log(await p2);
})();

Example

function wait(value, ms) {
  return new Promise((resolve) => {
    setTimeout(() => resolve(value), ms);
  });
}
(async () => {
  console.log("Sequential:");
  console.log(await wait("One", 50));
  console.log(await wait("Two", 50));
  console.log("Parallel:");
  const both = await Promise.all([wait("Three", 50), wait("Four", 50)]);
  console.log(both.join(" "));
})();

Key points

  • Sequential: awaits written one after another, so each waits for the last
  • Parallel: promises started together, then awaited with Promise.all
  • Sequential work takes the sum of the waiting times.
  • Parallel work takes only the longest single waiting time.
  • Start a promise before awaiting it to let it run while other code works.

In this example, the first two awaits run one after another, so One logs before Two. The Promise.all pair starts together, so Three and Four arrive as one list. The order of the lines shows which pattern ran.

Note

Awaited one by one, two promises still log in await order, even when the second finishes first.

Try it Yourself

Edit the code, then press Run.

Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

How do two awaits run in parallel?