Skip to content

Instantly share code, notes, and snippets.

@craigmr
Last active August 29, 2015 14:20
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save craigmr/c83320db1d230210b8b3 to your computer and use it in GitHub Desktop.
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