Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Chained Async Calls to Prevent Race Conditions
/**
* calculateZChained() Chain the two aysnc calls together to fix the race condition.
*/
function calculateZChained() {
let x = 0, y = 0, z;
//Async call to get the true value of y
setTimeout(() => {
y = 2;
//Async call to calculate z using value of x and y.
setTimeout(() => {
x = 2;
z = x + y;
console.log(z);
}, Math.random() * 1000);
}, Math.random() * 1000);
}
//Lets run it a 100 times. This out simulate us refreshing the browser a few times.
for (let i = 0; i < 100; i++) {
calculateZ();
}
//Because we call one aysnc after another we get the correct value everytime!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment