How to avoid async race conditions in JavaScript

fetch(url)
.then(data => data.json())
.then(items => updateState(items));
if (this.lastRequest) {
clearTimeout(this.lastRequest);
}
this.lastRequest = setTimeout(() => {
updateState([1,2,3]);
this.lastRequest = null;
}, 5000);
const currentSession ={};
this.lastSession = currentSession;
fetch(url)
.then(data => data.json())
.then(items =>{
if (this.lastSession !== currentSession) {
return;
}
updateState(items);
}).catch(error =>{
if (this.lastSession !== currentSession){
return;
}
setError(error);
});

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store