Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Promise Async Calls to Prevent Race Conditions
/**
* 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