public
Last active

the beauty of promises

  • Download Gist
1_before.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11
// Before introducing promises, each of these functions required a callback to be passed in to it.
// This leads to deeply nested structures and the arrow-anti-pattern, creating more visual complexity
// and reducing the maintainability of this code
 
Tiles.getImagesForTile(function(images){
Tiles.buildThumnails(images, function(thumbnails){
Tiles.transmogrify(thumbnails, function(notification){
updater.update(notification);
}
});
});
2_after.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// After introducing promises, the methods can be chained together easily,
// reducing the nesting and the visual complexity of the code. This allows
// the code to be more easily understood, and therefore easier to maintain.
 
// Each of these functions still receives the same first-position parameter,
// but none of them needs to receive a second parameter as a callback. They
// each return a promise instead of using callbacks.
 
Tiles.getImagesForTile()
.then(Tiles.buildThumbails)
.then(Tiles.transmogrify)
.then(function (notification) {
updater.update(notification);
});

For these cases I find reduce can be quite nice as well... taken from the Q docs which is an awesome promises implementation. Their docs are excellent for understanding the implementation of promises too.

var funcs = [foo, bar, baz, quux];

return funcs.reduce(function (soFar, f) {
    return soFar.then(f);
}, Q.resolve(initialVal));

now that's an interesting approach! i haven't seen that before. :)

I wish I could take credit :-) take a look at this documentation for some great uses of promises. https://github.com/kriskowal/q/

With the async.js library and node-style callbacks this would be

async.waterfall([
  Tiles.getImagesForTile,
  Tiles.buildThumbnails,
  Tiles.Transmogrify,
  updater.update], function (error, results) {});

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.