如何解决减速器中异步函数数组的多重承诺?
How to resolve a multiple promises for an array of async functions in a reducer?
我在 js 中有一个高阶函数,它接受一个异步函数数组、传递给第一个函数的 n 参数和一个打印最后一个函数返回的承诺结果的回调函数。第一个函数会将结果传递给第二个函数,但它需要等到它完成等等。问题是只有第一个 promise 得到解决,其余的 promise 悬而未决。我如何“链接”这些回调的承诺而不是打印 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);
您可以使用 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);
})
我在 js 中有一个高阶函数,它接受一个异步函数数组、传递给第一个函数的 n 参数和一个打印最后一个函数返回的承诺结果的回调函数。第一个函数会将结果传递给第二个函数,但它需要等到它完成等等。问题是只有第一个 promise 得到解决,其余的 promise 悬而未决。我如何“链接”这些回调的承诺而不是打印 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);
您可以使用 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);
})