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:

async function sequence() {
  const output1 = await a();
  const output2 = await b();
  const output3 = await c();
  return `sequence is done ${output1} ${output2} ${output3}`
}
sequence().then(console.log); // sequence is done: a b c

Race:

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

Last updated