Skip to content

Instantly share code, notes, and snippets.

@rstacruz
Last active December 18, 2015 13:39
Show Gist options
  • Save rstacruz/5791320 to your computer and use it in GitHub Desktop.
Save rstacruz/5791320 to your computer and use it in GitHub Desktop.
Promises vs Callbacks
// --------------------------------------------------------------------
// 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); }
// --------------------------------------------------------------------
// 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);
})
// --------------------------------------------------------------------
// 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