Chained Async Calls to Prevent Race Conditions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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