Created
December 10, 2016 02:03
-
-
Save ericelliott/ffc954c05a5cad2116ef8f5e4496257d to your computer and use it in GitHub Desktop.
Promise example
This file contains 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
const doSomething = (err) => new Promise((resolve, reject) => { | |
if (err) return reject(err); | |
setTimeout(() => { | |
resolve(42); | |
}, 1000); | |
}); | |
const log = value => console.log(value); | |
// Using returned promises | |
doSomething().then( | |
// on resolve: | |
log, // logs 42 | |
// on reject (not called this time) | |
log | |
); | |
// remember to handle errors! | |
doSomething(new Error('oops')) | |
.then(log) // not called this time | |
.catch(log); // logs 'Error: oops' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What's your opinion of just renaming line 9 to simply
const log = console.log
, or even omitting that line and just simply using console.log directly within the promises? You can save a line of code (>5% of the example), though learners would miss the opportunity of seeing the arrow syntax at work. Is there any other benefit for declaring your own log function in this case?