Question:
How to avoid duplicate parallel API calls using Promises in JavaScript?


Problem

I'm currently working on a frontend script that fetches data from an API. To optimize performance, I implemented Promises. Once an API call is made for a specific parameter, the results are stored in a variable, and subsequent requests for the same parameter are resolved using the previously fetched data.


The current code looks like this


let _knownData = [];

function callAPI(param) {

    return new Promise((resolve, reject) => {

        let find = _knownData.find(x => x.param === param);

        if (find) {

            resolve(find.response);

        } else {

            fetch (API_URL, {param: param}). then(response => {

                // process response into res and cache it

                .....

                if (res) {

                    _knownData.push({ param: param, response: res });

                    resolve(res);

                } else {

                    reject(false);

                }

            })

        }

    });

}



callAPI(param1).then( ... )

callAPI(param2).then( ... )


This works well unless two requests for the same parameter are made in parallel. In such a scenario, the API is called twice because the second request is initiated before the first one is resolved and stored in the cache variable.


I want to achieve a scenario where only one API call per unique parameter is made, and any subsequent requests for the same parameter will wait for the first promise to resolve. I'm looking for a solution that doesn't overly complicate the code.


Solution

Store the promise instead of waiting for the final result.


const _knownData = {};

function callAPI(param) {

    if (_knownData[param]) return _knownData[param];

    const promise = fetch(API_URL, {param});

    _knownData[param] = promise;

    return promise;

}


Note that the if (res) logic you have in the original code is pointless. res will never not be a truthy value.


Suggested blogs:

>How to use querySelectorAll()" with multiple conditions in JavaScript?

>How to fix mouseover event glitch in JavaScript?

>How to do light and dark mode in a website using HTML and JavaScript?

>How to manipulate manipulating Array object in JavaScript?

>How to merge an object into Array with the same key in JavaScript?

>Javascript Error Solved: Property 'id' does not exist on type 'T'

>Why highlighted table row using class not working in JavaScript?

>How to rename an object key based on the condition in JavaScript?

>How to sort an array based on another array in Javascript?

>Javascript: Modal not closing with a button


Nisha Patel

Nisha Patel

Submit
0 Answers