Skip to content

Instantly share code, notes, and snippets.

@mxriverlynn
Created July 18, 2012 15:08
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mxriverlynn/3136752 to your computer and use it in GitHub Desktop.
Save mxriverlynn/3136752 to your computer and use it in GitHub Desktop.
the beauty of promises
// 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);
}
});
});
// 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);
});
@iammerrick
Copy link

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));

@mxriverlynn
Copy link
Author

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

@iammerrick
Copy link

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

@focusaurus
Copy link

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) {});

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