How to avoid async race conditions in JavaScript

Slava Shpitalny
Jan 17, 2017 · 5 min read

Background…

fetch(url)
.then(data => data.json())
.then(items => updateState(items));

The problem…

Some solutions…

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);
});

Summary…

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade