Sequential Promise

Viewed 198

so I am trying to execute my promises sequentially without using async below is my code

//promises is an array of function who return a promise
const p = function(promises){
    let result = promises.reduce((prevPromise, promise) => {
        return prevPromise.then(res => {
            return promise.then(Array.prototype.concat.bind(res))
        })
    }, Promise.resolve([]));
    return result;
}

now say promises array has 2 functions which execute in 5 and 10 secs respectively, above code is giving answer in 10 secs but if true sequence execution should give in 15 secs. Please suggest.

2 Answers

In my opinion. promises.reduce just chained the promise but did not delay the perform time.

The promise perform time is when you create new Promise()

Create new promise in your then statement.

This is because you are reducing an array of promises instead of an execution of an asynchronous operations that returns a promise.

Take the example below, where we have a delay() function that returns a promise, performing an asynchronous setTimeout() operation where it resolves the ms delay after the timeout.

// a function that returns a promise that will only resolve
// after the setTimeout has finished.
const delay = ms => new Promise(resolve => setTimeout(
  resolve,
  ms,
  ms
));

// array of milliseconds to execute the delay() function
const items = [5000, 10000];

// timer to track the amount of time 
// passed after all delays are executed
console.time('delay');

// Reducing all promises wherein items are the delayed timeout
// while also the items that will be added in this reduction
const promise = items.reduce((promise, value) =>
  // wait for promise to resolve
  promise.then(result => 
    // perform async operation
    delay(value)
      // add each resolved value
      .then(item => result + item)
  ),
  // default value of reduction
  Promise.resolve(0)
);

promise.then(result => {
  // Should be the summation of the items array
  console.log('result', result);
  // show the time tracker if all of these operations
  // really finished appropriately.
  console.timeEnd('delay');
});

Related