Promise 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
/** | |
* calculatePromise() Use promises to get x and y values, now we can run our | |
* async tasks in parallel using Promise.all. Once we have both values | |
*/ | |
function calculatePromise() { | |
var y = new Promise((resolve, reject) => { | |
setTimeout(() => resolve(2), Math.random() * 1000); | |
}); | |
var x = new Promise((resolve, reject) => { | |
setTimeout(() => resolve(2), Math.random() * 1000); | |
}); | |
//Get values of y and x and then calulate z | |
Promise.all([y, x]) | |
.then(result => result[0] + result[1]) | |
.then(z => console.log(z)); | |
} | |
//Lets run it a 100 times. This out simulate us refreshing the browser a few times. | |
for (let i = 0; i < 100; i++) { | |
calculateZ(); | |
} | |
//Success! We've run both asyncs in parallel and correctly calculate z everytime! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment