bniwredyc
bniwredyc

Reputation: 8839

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?

Upvotes: 5

Views: 641

Answers (1)

Bergi
Bergi

Reputation: 665155

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?

Upvotes: 4

Related Questions