Skip to content

Instantly share code, notes, and snippets.

@Sleavely
Last active August 11, 2017 12:14
Show Gist options
  • Save Sleavely/4b32900c9ce555b73321ed1c96c01ab1 to your computer and use it in GitHub Desktop.
Save Sleavely/4b32900c9ce555b73321ed1c96c01ab1 to your computer and use it in GitHub Desktop.
Callback hell be gone!
// An example in classic callback hell.
// In this example, talkToAPI uses a callback like we're used to
talkToAPI('login', function(err, res){
doStuff(res);
talkToAPI('getUser', function(err, res){
doStuff(res);
talkToAPI('extraData', function(err, res){
doStuff(res);
talkToAPI('saveChanges', function(err, res){
doStuff(res);
talkToAPI('reloadUser', function(err, res){
doStuff(res);
});
});
});
});
});
// Instinctively, we want to do something similar with promises.
// In this example, talkToAPI returns a Promise instead of using a callback.
talkToAPI('login')
.then(function(res){
doStuff(res);
talkToAPI('getUser')
.then(function(res){
doStuff(res);
talkToAPI('extraData')
.then(function(res){
doStuff(res);
talkToAPI('saveChanges')
.then(function(res){
doStuff(res);
talkToAPI('reloadUser')
.then(function(res){
doStuff(res);
// As you can see, this is even worse in terms of clutter. But don't worry, it gets better.
})
.catch(function(err){
});
})
.catch(function(err){
});
})
.catch(function(err){
});
})
.catch(function(err){
});
})
.catch(function(err){
});
// Now this is how we can use the beauty of promises.
// In this example, talkToAPI() returns a Promise.
talkToAPI('login')
.then(function(res){
doStuff(res);
return talkToAPI('getUser'); // Return a new promise that will have to resolve before the next .then() is called
})
.then(function(res){
doStuff(res);
return talkToAPI('extraData');
})
.then(function(res){
doStuff(res);
return talkToAPI('saveChanges');
})
.then(function(res){
doStuff(res);
return talkToAPI('reloadUser');
})
.then(function(res){
doStuff(res);
})
.catch(function(err){
});
@niteng
Copy link

niteng commented Aug 11, 2017

Wuv it!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment