Nisha Patel
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
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.
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