1

I would like to know how to solve running an array of promises using async, in sequential order, but specifically how to pass the resolved value from one function to the next.

All the examples I have seen so far just show something like this:

const value = await foo();
const value2 = await bar(value);

I'd prefer to do run them all together sequentially from an array, but just not sure how to pass the returned values between them (since I'm trying to use vanilla js async here).

JackDev
  • 4,891
  • 1
  • 39
  • 48
  • What do you mean “all together” and “sequentially”? – evolutionxbox Oct 08 '18 at 07:55
  • I mean that to get `value2`, I need to first get `value`. But I want to run them from an array of promise functions ie [foo, bar]. I currently have two, but I may want to run them through a sequence of 10 functions, each one transforming the input and passing the transformed data to the next one, until the data has run through all the functions in the array – JackDev Oct 08 '18 at 07:58
  • Possible duplicate of [How can I execute array of promises in sequential order?](https://stackoverflow.com/questions/20100245/how-can-i-execute-array-of-promises-in-sequential-order) – Weedoze Oct 08 '18 at 08:01
  • That does not use vanilla JS (as I understand it since it uses RSVP, Q, etc), also it just calls the functions, it does not seem to show the returned values in the for loop. – JackDev Oct 08 '18 at 08:03

2 Answers2

3

You can create a pipeline like this:

let fnArray  = [foo,  bar, baz];
let lastResult;
for(let i = 0; i < fnArray.length; i++) {
     lastResult = await fnArray[i](lastResult);
}
Ayush Gupta
  • 8,716
  • 8
  • 59
  • 92
1

Wrap them in a .then()

foo()
    .then(valueFoo => bar(valueFoo))
    .then(valueBar => AnotherFunc(valueBar))
    .catch(e => { console.log(e)})
Domenik Reitzner
  • 1,583
  • 1
  • 12
  • 21
Nelson Owalo
  • 2,324
  • 18
  • 37