How is async/await working in serial and parallel?

Viewed 4086

I have two async functions. Both of them are waiting for two 3 seconds function calls. But the second one is faster than the first. I think the faster one is running in parallel and other in serial. Is my assumption correct? If yes, why is this happening as both the functions look logically same?

function sleep() {
  return new Promise(resolve => {
    setTimeout(resolve, 3000);
  });
}

async function serial() {
  await sleep();
  await sleep();
}

async function parallel() {
  var a = sleep();
  var b = sleep();
  await a;
  await b;
}

serial().then(() => {
  console.log("6 seconds over");
});

parallel().then(() => {
  console.log("3 seconds over");
});
4 Answers

Serial Run: Run the functions one after another

//  It’s slow! and use only for serial(one after another) run
async function doThings() {
    const thing1 = await asyncThing1(); // waits until resolved/rejected
    console.log(thing1);

    const thing2 = await asyncThing2(); // starts only after asyncThing1() has finished.
    console.log(thing2);
}

doThings();

Parallel Run: Run the functions parallel

// ✅ async code is run in parallel!
async function doThings() {
    const p1 = asyncThing1(); // runs parallel
    const p2 = asyncThing2(); // runs parallel


    // Method 1: Prefer => Promise.all()
    const [resultThing1, resultThing2] = await Promise.all([p1, p2]); // waits for all 
    // the promises get resolved or fails fast (If one of the promises supplied to it 
    // rejects, then the entire thing rejects).

    // Method 2: Not-Preferred
    const resultThing1 = await p1;
    const resultThing2 = await p2;

    console.log(resultThing1); // reaches here only after both the p1 & p2 have completed.
    console.log(resultThing2);
}

doThings();
Related