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

180
Vistas
Why isn't this function fast when we collect result from async call?
const services = ['a', 'b', 'c', 'd'];

async function foo(service) {

    // function to get one jobUrl data called by map later on
    const getJob = async ({ url: jobUrl }) => {
        const response = await fetch(jobUrl, { headers: headers });
        const { result, timestamp: timeStamp } = await response.json();
        if (result === 'SUCCESS') {
            return { jobUrl, timeStamp };
        }
    };

    // Find the list of jobs for a service
    let url = `http://example.com`;
    const response = await fetch(url, { method: 'POST', headers: headers });
    const { jobs } = await response.json();

    const unfiltered = await Promise.all(jobs.map(getJob));
    const successful = unfiltered.filter(v => v);

    let latestJob = successful.sort((obj1, obj2) => obj2.timeStamp - obj1.timeStamp)[0].jobUrl;
    let arr = latestJob.split('/');
    let recent = { service: service, job: arr[arr.length - 2] };
    console.log(recent);
    // return recent; 
}

When I run the following piece of code it takes only 4 seconds for finding the latest job.

for (const service of services) {
    foo(service);
}

Whereas, when I run the following piece of code it takes 15-16 seconds for finding the latest job. For this I uncomment the return recent; line of code in the last line of function foo and comment out the console.log(recent) line.

const latest = [];
for (const service of services) {
    latest.push(await foo(service));
}

My understanding is that for the second piece of code since we are waiting for all the async calls to finish it takes longer. If that is the case, is there a way to speed this up?

about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

You may want to use Promise.all or Promise.allSettled.

That way you can pass an array of async functions (promises) and await them. That way, functions are not running sequentially but async.

about 4 years ago · Santiago Trujillo 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