Last active
December 26, 2015 22:09
-
-
Save meagar/7221284 to your computer and use it in GitHub Desktop.
A simply way of DRYing up promise-returning functions
This file contains hidden or 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
# There's an incredibly common pattern when using promises: | |
# | |
# myFunction: -> | |
# dfd = $.Deferrred() | |
# | |
# $.ajax "wherever" | |
# .done() -> | |
# dfd.resolve("yep") | |
# .fail() -> | |
# dfd.reject("nope") | |
# | |
# dfd.promise() | |
# | |
# The particularly repetative bits are: | |
# | |
# dfd = $.Deferred() | |
# # ... | |
# dfd.promise() | |
# | |
# It's a little tiresome to constantly create deferreds and return their promises, so here's | |
# a conviencince method which does that much for you: | |
# | |
# myFunction: promises (dfd) -> | |
# $.ajax "whatever" | |
# .done -> | |
# dfd.resolve() | |
# .fail -> | |
# dfd.reject() | |
# | |
# It works with arguments, and in class declarations: | |
# | |
# class MyClass | |
# showName: promises (dfd, name) -> | |
# setTimeout (-> alert(name); dfd.resolve()), 1000 | |
# | |
# The only wrinkle is that it hides the parent class from CoffeeScript's `super` keyword, so you | |
# have to use an alternate syntax: | |
# | |
# class MyChildClass extends MyClass | |
# showName: (name) -> | |
# promises (dfd) => | |
# super | |
exports = this | |
exports.promises = (callback) -> | |
(args...) -> | |
dfd = $.Deferred() | |
args.unshift(dfd) | |
callback.apply(@, args) | |
dfd.promise() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment