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?

2
  • 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. Commented Aug 10, 2020 at 19:00
  • use promise all Commented Aug 10, 2020 at 19:09

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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); } } 

3 Comments

You forgot to pass data from one function to another.
@Evert impossible without async-await?
I tried to rewrite it with what I think you want. It's certainly possible without async/await but I'm sharing this as a valid solution that's likely the most readable.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.