Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

162
Views
javascript map with reduce while calling async

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)
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!