Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert function call with two callbacks to promise

I have a function like this:

var f = function(options, successCallback, errorCallback) {
   ...
}

and I want to convert it's call to a promise. My current solution is this:

var deferred = Q.defer();

f(options,
    function (result) {
        deferred.resolve(result);
    }, function (err) {
        deferred.reject(err);
    }
);

return deferred.promise;

I can't use the Q.fcall because it expects a Node.js-style callback function(err, result) { ... }

So, is there a way to improve my code using the Q API?

like image 859
bniwredyc Avatar asked Sep 29 '22 16:09

bniwredyc


1 Answers

No, all these helper functions (based on Deferred.makeNodeResolver) are only there to deal with the ugly nodebacks. If the callback-style method already takes separate success and error callbacks not much extra work needs to be done.

You could simplify your pattern by removing those unnecessary closure function expressions:

var deferred = Q.defer();
f(options, deferred.resolve, deferred.reject);
return deferred.promise;

You could also use the Promise constructor, which is the preferred method for promise creation (bonus: catches exceptions thrown by f):

return new Q.Promise(function(resolve, reject) {
    f(options, resolve, reject);
});

which might even be shortened with partial application to

return new Q.Promise(f.bind(null, options));

See also the generic reference: How do I convert an existing callback API to promises?

like image 94
Bergi Avatar answered Oct 17 '22 05:10

Bergi