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

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

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 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