Promises Execution

Three different ways to execute promises.

  1. Parallel - all at a time

  2. Sequence - one by one

  3. Race - who comes first

// Basic Data
const promisify = (item, delay) =>
  new Promise((resolve) =>
    setTimeout(() =>
      resolve(item), delay));

const a = () => promisify('a', 100);
const b = () => promisify('b', 5000);
const c = () => promisify('c', 3000);

Parallel:

async function parallel() {
  const promises = [a(), b(), c()];
  const [output1, output2, output3] = await Promise.all(promises);
  return `prallel is done: ${output1} ${output2} ${output3}`
}
parallel().then(console.log); // prallel is done: a b c

Sequence:

Race:

Last updated

Was this helpful?