JavaScript
  • JavaScript Introduction
  • JS Engine
  • V8 Engine
  • First-class function
  • Optimized Code
  • Call Stack & Memory heap
  • Single Thread
  • JavaScript RunTime
  • Nodejs
  • Context and Environment
  • Hoisting
  • Functions
  • Arguments
  • Variables
  • Scope
  • IIFE
  • this
  • call(), apply() and bind()
  • currying
  • Types
  • Type Coercion
  • Functions as Object
  • HOF (Higher Order Function)
  • Two pillars of Javascript
  • Closures
  • Prototypal Inheritance
  • OOP and FP
  • OOP
    • 4 principles of OOP
  • FP
    • Pure function
    • Imperative vs Declarative
    • Immutability
    • HOF and Closures
    • Currying
    • Partial Application
    • Compose and Pipe
  • Composition vs Inheritance
  • OOP vs FP
  • JS working
  • Promises
  • Async Await
  • ES5 - ECMAScript 2009
  • ES6 - ECMAScript 2015
  • ES7 - ECMAScript 2016
  • ES8 - ECMAScript 2017
  • ES9 - ECMAScript 2018
  • ES10 - ECMAScript 2019
  • ES11 - ECMAScript 2020
  • ES12 - ECMAScript 2021
  • JOB Queue
  • Promises Execution
Powered by GitBook
On this page

Was this helpful?

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
PreviousJOB Queue

Last updated 5 years ago

Was this helpful?