Created
July 18, 2012 15:08
-
-
Save mxriverlynn/3136752 to your computer and use it in GitHub Desktop.
the beauty of promises
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
// 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); | |
} | |
}); | |
}); |
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
// 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); | |
}); |
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) {});
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
now that's an interesting approach! i haven't seen that before. :)