Skip to content

Instantly share code, notes, and snippets.

@ada-lovecraft
Last active January 1, 2016 07:59
Show Gist options
  • Save ada-lovecraft/8115700 to your computer and use it in GitHub Desktop.
Save ada-lovecraft/8115700 to your computer and use it in GitHub Desktop.
The Power of Promises
// Promises on their own seem to be cumbersome compared to basic callbacks
a = new DataService(aUrl);
// Single Callback
a.async(function(data) {
doAfter(data);
});
// Single Promise
a.async().then(function(data) {
doAfterA(data);
}, function() {
console.error('a failed to load');
})
// This seems easy enough, right?
// But what if you want to load two async calls before continuing ?
b = new DataService(bUrl);
a.async(function(aData) {
b.async(function bData) {
doAfterA(aData);
doAfterB(bData);
doAfterAll();
}
})
// What if you have a service that hits 5 different repositories to get data?
// (This of course would be bad api design, but since this is an academic discussion...)
// You can see from the previous example that you'd quickly end up in callback hell thusly
c = new DataService(cUrl);
d = new DataService(dUrl);
e = new DataService(eUrl);
a.async(function(aData) {
b.async(function (bData) {
c.async(function (cData) {
d.async(function(dData){
e.async(function(dData){
doAfterA(aData);
doAfterB(bData);
doAfterC(cData);
doAfterD(dData);
doAfterE(eData);
doAfterAll();
})
})
})
})
})
// Promises fix this issue
// and allow for cleaner code
a.async().then(function(data) {
// loaded successfully
doAfterA(aData)
}, function() {
// error
console.error('a failed to load')
})
b.async().then(function(data) {
// loaded successfully
doAfterB(data)
}, function() {
// error
console.error('b failed to load')
})
c.async().then(function(data) {
// loaded successfully
doAfterC(data)
}, function() {
// error
console.error('c failed to load')
})
d.async().then(function(data) {
// loaded successfully
doAfterD(data)
}, function() {
// error
console.error('d failed to load')
})
e.async().then(function(data) {
// loaded successfully
doAfterE(data)
}, function() {
// error
console.error('e failed to load')
})
// AND THE MONEY SHOT
// "Wait" until all async calls have completed before continuing
Promise.all([a.async(), b.async(), c.async(), d.async(), e.async()]).then(function() {
// all loaded
doAfterAll();
}, function() {
// one or more failed
console.error('Promise failed to resolve.')
});
@ada-lovecraft
Copy link
Author

Pardon my lack of semicolons. I tend to write most of my code in coffeescript.

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