Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

193
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!