I have two buttons for triggering requests, both of which are data requests to the same API, with different buttons representing different parameters.
For example, button A is requesting data for the year 2023 and button B is requesting data for the year 2022:
// Click button A
fetch('same/api', {
body: {
year: 2023
}
}).then(res => {
store = res;
})
// Click button B
fetch('same/api', {
body: {
year: 2022
}
}).then(res => {
store = res;
})
The store
variable is used to store the response data.
My question is: When I click button A and then click button B in a very short interval, will the response result of button A overwrite the response result of button B? If so, how can I solve such a defect?
I have created a simple demo on codepen: simple demo.
Issue update: Out-of-date responses incorrectly overwrite the correct results, and the question now is how to fix this flaw. Existing solutions:
- use a synchronization primitive
- use an object or a map to store the results separately with an identifier
- discard the request
Does anyone know which method is better? Or is there another way to solve this problem?