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?
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 throw
n 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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With