5

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?

bniwredyc
  • 8,649
  • 1
  • 39
  • 52

1 Answers1

4

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?

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375