Skip to content

Instantly share code, notes, and snippets.

@Sinetheta
Created October 4, 2016 07:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sinetheta/66b4eba681358cf0c473e80350a3cf8a to your computer and use it in GitHub Desktop.
Save Sinetheta/66b4eba681358cf0c473e80350a3cf8a to your computer and use it in GitHub Desktop.
A jquery plugin for wrapping a function with a promise
// 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();
};
@NYCMEL
Copy link

NYCMEL commented Aug 25, 2018

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

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