Last active
May 5, 2016 22:18
-
-
Save santiago-puch-giner/5f7152375b5fee77905ae1a69f73f998 to your computer and use it in GitHub Desktop.
Promises in Javascript ES6
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
| // Snippet for Promises (ES6) | |
| // Create a Promise that is resolved and handle it using "then" methods | |
| let p = new Promise( (resolve, reject) => { | |
| setTimeout( () => { | |
| resolve("Good to go!"); | |
| }, 1000); | |
| }); | |
| p.then( | |
| (data) => { | |
| console.log(data); | |
| }, | |
| (err) => { | |
| console.log(err); | |
| } | |
| ); | |
| // Create a Promise that is rejected and handle it using "then" and "catch" methods | |
| // Here we can see that, even if we have a resolve and a reject, if the promise | |
| // has already changed to a "resolved" or "rejected" state it cannot change | |
| // its state any more. That's why we only see the rejected value. | |
| let p2 = new Promise( (resolve, reject) => { | |
| setTimeout( () => { | |
| resolve("Good to go!"); | |
| }, 1000); | |
| setTimeout( () => { | |
| reject("Oops that didn't go well..."); | |
| }, 500); | |
| }); | |
| p2.then( (data) => { | |
| console.log(data); | |
| }).catch( (err) => { | |
| console.log(err); | |
| }); | |
| // Handle the resolved state of several promises | |
| Promise.all([p, p2]) | |
| .then( (data) => { | |
| console.log(data); | |
| }) | |
| .catch( (err) => { | |
| console.log(err); | |
| }); | |
| // Visit https://promisesaplus.com/ for more information |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment