Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

163
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda