Search code examples
javascriptasynchronouscallbackes6-promisehigher-order-functions

How to resolve a multiple promises for an array of async functions in a reducer?


I have a higher-order function in js that takes an array of asynchronous functions, n parameter which is passed to the first function and a callback function that prints the result from the promise returned by the last function. First function will pass the result to the 2nd one but it needs to wait until it's finished and so on. The problem is only the first promise gets resolved and the rest of the promises are pending. How can I "chain" these promises for the callback not to print NaN but actual value ("chain" in this function, not manually, I know I can do this with .then() but if I have a bigger array it's not gonna be effective)?

const functionsInSequence = (funTab, cb) => (n) => {
    const lastPromise = funTab.reduce((acc, fn) => {
        return new Promise(resolve => 
            fn(acc).then(value => {
                resolve(value);
            })
        )
    }, n);
    cb(lastPromise);
};



const functions = [
    async x => x * 2,
    async x => x * 3,
    async x => x * 4,
];

const myCb = (promise) => {
    promise.then(value => console.log("val:", value));
}

functionsInSequence(functions, myCb)(2);

Solution

  • You can use async/await syntax to make code more readable. You can loop through the functions array and await for each response before continue. You can do it like this:

    const functions = [
      async x => x * 2,
      async x => x * 3,
      async x => x * 4,
    ];
    
    const resolveAll = async (input) => {
      let result = input;
      for (let index = 0; index < functions.length; index++) {
        result = await functions[index](result);
        console.log(`${index+1}. function result: `, result)
      }
      return result;
    }
    
    
    resolveAll(5).then((result)=>{
      console.log('Final Result: ', result);
    })