Skip to content

Instantly share code, notes, and snippets.

@dnasca
Created September 18, 2015 07:45
Show Gist options
  • Select an option

  • Save dnasca/e9d8b8520ba8a25b68f4 to your computer and use it in GitHub Desktop.

Select an option

Save dnasca/e9d8b8520ba8a25b68f4 to your computer and use it in GitHub Desktop.
async cb w/ promises in es2015!
//the most basic async cb
sleep = function(ms) {
let promise = new Promise(function(resolve, reject) {
setTimeout(function() {
resolve("the result");
}, ms);
});
return promise;
};
sleep(1000)
.then((result) => sleep(1000)) //1st execution after 1 second
.then((result) => console.log("2: " + result)); //2nd execution after another 1 second
.catch((err) => console.log("error: " + err));
//wait for everything to complete
Promise.all([sleep(1000), sleep(2000)])
.then(() => console.log("all done")); //printed 2nd
//wait for the 1st promise to complete, then, call the then callback
Promise.race([sleep(1000), sleep(2000)])
.then(() => console.log("race")); //printed 1st
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment