【问题标题】:How to resolve a multiple promises for an array of async functions in a reducer?如何解决减速器中一组异步函数的多个承诺?
【发布时间】:2021-06-01 22:01:03
【问题描述】:

我在 js 中有一个高阶函数,它接受一个异步函数数组,传递给第一个函数的 n 参数和一个回调函数,它打印最后一个函数返回的承诺的结果。第一个函数会将结果传递给第二个函数,但它需要等到它完成,依此类推。问题是只有第一个承诺得到解决,其余的承诺正在等待。我怎样才能“链接”回调的这些承诺而不是打印 NaN 而是实际值(在这个函数中“链”,而不是手动,我知道我可以用 .then() 来做到这一点,但如果我有一个更大的数组,它就不会有效)?

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

【问题讨论】:

标签: javascript asynchronous callback es6-promise higher-order-functions


【解决方案1】:

您可以使用async/await 语法使代码更具可读性。在继续之前,您可以循环遍历每个响应的 functions 数组和 await。你可以这样做:

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

【讨论】:

    猜你喜欢
    • 2019-04-13
    • 2020-07-04
    • 2018-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多