Last active
August 11, 2017 12:14
-
-
Save Sleavely/4b32900c9ce555b73321ed1c96c01ab1 to your computer and use it in GitHub Desktop.
Callback hell be gone!
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
// 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); | |
}); | |
}); | |
}); | |
}); | |
}); |
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
// 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){ | |
}); |
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
// 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){ | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Wuv it!