javascript 调用异步时使用 reduce 进行映射
javascript map with reduce while calling async
我需要在映射函数回调中调用异步函数 f。我也想在之后应用 reduce 但无法使其工作:
const a = [1, 2];
async function f() {}
let test = a.map(
async (x, i) => {
await f();
let val = x;
alert(val)
return val;
}
).reduce((result, element) => result + element)
使用Promise.all
等待异步映射,然后return reduce
的结果。请注意,在此示例中,test
也将 return 一个承诺,因此您需要 await
其结果才能记录它。
const a = [1, 2];
async function f() {}
async function test() {
const mapping = a.map(async (x, i) => {
await f();
return x;
});
const result = await Promise.all(mapping);
return result.reduce((acc, c) => acc + c, 0);
}
async function main() {
console.log(await test())
}
main();
我需要在映射函数回调中调用异步函数 f。我也想在之后应用 reduce 但无法使其工作:
const a = [1, 2];
async function f() {}
let test = a.map(
async (x, i) => {
await f();
let val = x;
alert(val)
return val;
}
).reduce((result, element) => result + element)
使用Promise.all
等待异步映射,然后return reduce
的结果。请注意,在此示例中,test
也将 return 一个承诺,因此您需要 await
其结果才能记录它。
const a = [1, 2];
async function f() {}
async function test() {
const mapping = a.map(async (x, i) => {
await f();
return x;
});
const result = await Promise.all(mapping);
return result.reduce((acc, c) => acc + c, 0);
}
async function main() {
console.log(await test())
}
main();