2

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.

  • What's wrong with `async`/`await`? – Aluan Haddad Feb 28 '21 at 08:37
  • If you already have an array of promises, the only thing you can do is to wait for them (using `Promise.all`). If you want stuff to execute sequentially, that means you need **functions** that you can **call** sequentially. – Bergi Feb 28 '21 at 14:09

2 Answers2

0

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.

lei li
  • 1,244
  • 1
  • 12
  • 35
  • There are many reasons not to use the Promise constructor unnecessarily, but I doubt the performance impact is significant – Aluan Haddad Feb 28 '21 at 08:51
0

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');
});
ryeballar
  • 29,658
  • 10
  • 65
  • 74