Created
September 18, 2015 07:45
-
-
Save dnasca/e9d8b8520ba8a25b68f4 to your computer and use it in GitHub Desktop.
async cb w/ promises in es2015!
This file contains hidden or 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
| //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