0

PromisesInSeries function that takes an array of asynchronous functions and sequentially (the next one starts when the previous one has finished) calls them, passing the result of calling the previous function as arguments

function promisesInSeries(asyncFns) {
    let result;
    return new Promise((resolve, reject) => {
        for(const fn of asyncFns){
            resolve(fn)
            .then(data => fn(data))
        }
    })
}

I only get the results of the first function. How to call all functions from an array and, as a result, return the last value?

  • I am not sure, but *if this were possible*, I would think that you need to return an array of promises, not a promise with an array of calls. This is because *each* of the functions is async, so *each* will need an associated promise. – Mike Williamson Aug 10 '20 at 19:00
  • use promise all – epascarello Aug 10 '20 at 19:09

2 Answers2

0

If you can use async-await, this is way easier:

async function promisesInSeries(asyncFns) {
    let result;
    for (const fn of asyncFns) {
      result = await fn(result);
    }
}
Evert
  • 93,428
  • 18
  • 118
  • 189
0

Without async/await you could reduce the fns array:

function promisesInSeries(fns) {
  return fns.reduce((promise, fn) => promise.then(fn), Promise.resolve());
}

The first fn will receive the value undefined, after that each return value is passed to the next function.

If you want to have some initial value, you can provide it by changing Promise.resolve() to Promise.resolve(initialData). Where initialData could be a static value or a value passed through function parameters.

3limin4t0r
  • 19,353
  • 2
  • 31
  • 52