Skip to content

Instantly share code, notes, and snippets.

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