Sobes.tech
Middle+

What is the difference between sequential await p1, await p2 and Promise.all([p1, p2])?

sobes.tech AI

Answer from AI

When using await p1; await p2; sequentially, the code execution pauses first until p1 completes, then until p2. This means the second promise will only start executing after the first one has finished.

In the case of Promise.all([p1, p2]), both promises are started in parallel, and the code waits until both are completed. This is more efficient if the promises do not depend on each other.

Example:

async function sequential() {
  const result1 = await p1; // wait for p1
  const result2 = await p2; // wait for p2 after p1
  return [result1, result2];
}

async function parallel() {
  const [result1, result2] = await Promise.all([p1, p2]); // wait for both simultaneously
  return [result1, result2];
}

Summary: Promise.all allows promises to run in parallel, reducing total waiting time, while sequential await executes them one after the other.

What is the difference between sequential await p1… - sobes.tech