Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

164
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda