I need to call an async function f within map function callback. I also want to apply reduce after but can't make it work :
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)
CodePudding user response:
Use Promise.all
to await the async mapping, and then return the result of the reduce
. Note, in this example, test
will return a promise too so you'll need to await
the result from that before you can log it.
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();