3 ms·
Here's a contrived example: Promises: //model User.get = function() { return getData(); }; User.getOdd = function() { return User.get().then(f
by lhorie 13y ago
Here's a contrived example:
Promises:
//model
User.get = function() {
return getData();
};
User.getOdd = function() {
return User.get().then(filterOdd);
};
//controller
someControllerAction = function() {
User.getOdd().then(redirectToHomepageIfEmpty);
};
Callbacks:
//model
User.get = function(callback) {
getData(callback)
}
User.getOdd = function(callback) {
User.get(function(data) {
if (typeof callback == "function") {
callback(filterOdd(data));
}
});
};
//controller
someControllerAction = function() {
User.getOdd(redirectToHomepageIfEmpty)
};
Notice how there's a little bit of noise required in the callback version of User.getOdd - i.e. if (typeof callback == "function"). Ideally this kind of noise is something that should be hidden at a framework level, and not show up in application code.
Noise can get quite significant when the code is predominantly dealing with asynchrony, e.g. try implementing this in callback style:
jQuery.when(User.getOdd(), Pinterest.search("something")).then(doSomething)
It's doable, but it's messy, because the code that is supposed to be focused on pinterest items and odd users now also needs to deal with flags indicating which http request is done at which point.