Home > Back-end >  Why isn't this function fast when we collect result from async call?
Why isn't this function fast when we collect result from async call?

Time:08-25

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?

CodePudding user response:

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.

  • Related