Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading