Created
July 2, 2018 19:25
-
-
Save pbzona/8d86a76a26c817076450e3450523891b to your computer and use it in GitHub Desktop.
Alternate Promise Syntax
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
// Set up a promise | |
const promise = new Promise((resolve, reject) => { | |
const number = Math.floor(Math.random() * 2); | |
setTimeout(() => { | |
if (number > 0) { | |
resolve('Success!'); | |
} else { | |
reject('Failure!!!'); | |
} | |
}, 2000); | |
}); | |
const succeed = (data) => console.log(data); | |
const fail = (err) => console.error(err); | |
// Normal then/catch | |
promise | |
.then(succeed) | |
.catch(fail); | |
// ...but you can also do this: | |
promise.then(succeed, fail); | |
// The first way makes more sense semantically - you call the promise *then* do something, and you | |
// *catch* errors if they occur | |
// The second way shortens the final handling of the promise at the expense of immediate clarity. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment