Home > OS >  javascript map with reduce while calling async
javascript map with reduce while calling async

Time:10-01

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 :

https://www.typescriptlang.org/play?#code/MYewdgzgLgBAhjAvDA2gRgDQwEwF0DcAUHBAJ5jAwBmArhVAJbjUAUAlDAN4C hANgFNYUAdCTwAdAFs4ABxaEYSpSXKUWADywMOiAHxdFy43ADucBrCrsix44NgA3OH3EbbdlYIBOUFs742IyUASG8hGm8wGACPJV42CXCAExpgARYWcIgaPigsAUEpATAoXQNs3NgAahhCgWLSoKA

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

  • Related