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(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 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.
3
Answers
Store the promise instead of waiting for the final result.
Note that the
if (res)
logic you have in the original code is pointless.res
will never not be a truthy value.You can store the promises rather than store the data in the _knownData that way it will not know when two calls with exacts params are made in smaller time frame
I generally store the promise and then replace it with resolved value (I need that mainly for REPLing with it in devtools without async code)