0
let array = [
  new Promise((resolve, reject) =>{
    setTimeout(() => resolve(1), 2000) // 2 sec (Promise A)
  }),
  new Promise((resolve, reject) =>{
    setTimeout(() => resolve(2), 3000) // 3 sec (Promise B)
  }),
  new Promise((resolve, reject) =>{
    setTimeout(() => resolve(3), 1000) // 1 sec (Promise C)
  }),
  new Promise((resolve, reject) =>{
    setTimeout(() => resolve(4), 3000) // 3 sec (Promise D)
  })
];

I have above given array of promises, How to execute the given array of promises in sequential order, like - Promise A should get resolved before Promise B, C and D. Promise B should get resolved after Promise A and Before Promise B and C.

Promise B should get called only, if Promise A got settled by either success or failure. Promise C should get called only if Promise B gets settled...and so on. And the end it will return [1,2,3,4] as a result.

So, the Total time to execute all the promises from the array will take 2+3+1+3 =9 sec

Promise.sequentialOrderExecution = function (promises) {
  // implementation
}
Promise.sequentialOrderExecution.then(result => {
  console.log(result) // should print [1,2,3,4]
})

I tried but unable to solve this problem.

  • Use a for loop :) – Konrad Apr 17 '23 at 17:49
  • 2
    That is not going to happen with your code. If you want them to execute one after the other than you need to wait for them to get done. If they can run at the same time, you use Promise.all. – epascarello Apr 17 '23 at 17:49
  • 4
    Have you read e.g. https://stackoverflow.com/q/20100245/3001761? – jonrsharpe Apr 17 '23 at 17:50
  • 1
    One does not "call" or "execute" promises. They're the results of already-running tasks. – Bergi Apr 17 '23 at 18:01
  • 2
    All four timers are already ticking as soon as `let array` completes. In order to get the desired 9s delay, you need to wrap each into a function so you can control when it gets kicked off: `let array = [() => new Promise...]`. Then this works: `array.reduce((accuPromise, promiseWrapper) => accuPromise.then(accuResult => promiseWrapper().then(result => [...accuResult, result])), Promise.resolve([])).then(console.log)` – Amadan Apr 17 '23 at 18:06

0 Answers0