Create An Api Which Accepts A Callback, And Also Returns A Promise
So I'm trying to upgrade an existing api to support promises, but I want to maintain backwards compatibility. So, let's say this is my api: module.exports = { deliverPost: fun
Solution 1:
The answer is to use promise.nodeify
:
var q = require('q');
module.exports = {
deliverPost: function(callback) {
return q.nfcall(someAsyncFunction).catch(function(err) {
console.log(err);
throw err;
}).nodeify(callback);
}
}
Solution 2:
You could just test for a callback and run the callback code if it is present:
var q = require('q');
module.exports = {
deliverPost: function(callback) {
if(typeof callback === 'function'){
someAsyncFunction(function(err) {
if (err)
console.log(err);
callback(err);
});
}else{
return q.nfcall(someAsyncFunction).catch(function(err) {
console.log(err);
throw err;
});
}
}
Post a Comment for "Create An Api Which Accepts A Callback, And Also Returns A Promise"