Last active
December 18, 2015 13:39
-
-
Save rstacruz/5791320 to your computer and use it in GitHub Desktop.
Promises vs Callbacks
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
// -------------------------------------------------------------------- | |
// Standard callback-style | |
getUserID(function(err, id) { | |
User.find(id, function(err, user) { | |
Twitter.get('/statuses/user_timeline.json', user.username, function(err, data) { | |
console.log(data); | |
}); | |
}); | |
}); | |
// -------------------------------------------------------------------- | |
// What if you need to handle errors? | |
// Things get messy: | |
getUserID(function(err, id) { | |
if (err) { return error(err); } | |
User.find(id, function(err, user) { | |
if (err) { return error(err); } | |
Twitter.get('/statuses/user_timeline.json', user.username, function(err, data) { | |
if (err) { return error(err); } | |
console.log(data); | |
}); | |
}); | |
}); | |
function error(err) { console.error("Program derp:", err); process.exit(1); } |
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
// -------------------------------------------------------------------- | |
// Let's try it Promises-style | |
// (a'la Q.js) | |
getUserID() | |
.then(function(id) { | |
return User.find(id); | |
}) | |
.then(function(user) { | |
return Twitter.get('/statuses/user_timeline.json', user.username); | |
}) | |
.then(function(timeline) { | |
console.log(timeline); | |
}) | |
.fail(function(err) { | |
console.error("Derpity derp:", err); | |
process.exit(1); | |
}) |
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
// -------------------------------------------------------------------- | |
// What does that look like in CoffeeScript? | |
// Much cleaner! | |
getUserID() | |
.then (id) -> | |
User.find(id) | |
.then (user) -> | |
Twitter.get('/statuses/user_timeline.json', user.username) | |
.then (timeline) -> | |
console.log(timeline) | |
.fail (err) -> | |
console.error("Derpity derp:", err) | |
process.exit(1) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment