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.
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(res => {
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 scenario, the API is called twice because the second request is initiated before the first one is resolved and stored in 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.