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

168
Vistas
How can I invoke callback style functions concurrently?

(A prior version of this question was closed as a dup of how to invoke async functions in a loop. This version states clearly that the functions are not async)

I have several callback style functions which cannot be modified. Only changing the ABC function, how can I get the output in the same order as the function present in the D variable. I have tried using async-await but getting the output as ['123', 'ankit', '345'] because of the timeout event.

https://jsfiddle.net/ankitg1602/unrxv3k6

const A = (dev) => {
  setTimeout(() => {
    dev('ankit')
  }, 300)
}

const B = (dev) => {
  setTimeout(() => {
    dev('123')
  }, 50)
}

const C = (dev) => {
  setTimeout(() => {
    dev('345')
  }, 500)
}

const D = [A, B, C]

const ABC = (args, dev) => {
  // write your code here
  Promise.all(D.map(async (fun1) => {
    return await fun1(dev)
  }))
}

ABC(D, (result) => {
   console.log('result:', result) // ['ankit', 123, 345]
})
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The idea is to promisify the callback style functions. Below, a promise is created for each that resolves when the function calls its callback.

Map over promisfy to produce an array of async functions. Invoke each of them to collect an array of promises, then resolve the promises concurrently with Promse.all()

const A = (dev) => {
  setTimeout(() => {
    dev('ankit')
  }, 300)
}

const B = (dev) => {
  setTimeout(() => {
    dev('123')
  }, 50)
}

const C = (dev) => {
  setTimeout(() => {
    dev('345')
  }, 500)
}

const D = [A, B, C]

const ABC = async(args, dev) => {
  const promisify = fn => () => new Promise(resolve => fn(resolve));
  const promises = args.map(fn => promisify(fn)());
  Promise.all(promises).then(dev)
}

ABC(D, (result) => {
  console.log('result:', result) // ['ankit', 123, 345]
})

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