Created
October 4, 2016 07:04
-
-
Save Sinetheta/66b4eba681358cf0c473e80350a3cf8a to your computer and use it in GitHub Desktop.
A jquery plugin for wrapping a function with a promise
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
// Wrap a function and return a promise instead of accepting a callback. | |
// | |
// @param target [Function] the function to be wrapped. This function *must* | |
// accept a callback as its last argument of the form `function(err, data) {}`. | |
// @param args [Array] an array of the arguments for the target function. | |
// Not including the final callback, which will be provided by promisify. | |
// @return [Promise] A jQuery promise object which will resolve or reject | |
// based on the arguments passed to the callback. | |
function promisify(fun, args, self) { | |
var d = $.Deferred(); | |
fun.apply(self || this, (args || []).concat(function (err, data) { | |
err && d.reject(err); | |
d.resolve(data); | |
})); | |
return d.promise(); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you Sinetheta;
Was wondering if you send me an example usage of your wonderful "promisify"
I can not get it to work
thank you
-Mel