I'm not able to make a simple example works on bluebird. I've used the new Promise method and it works, but when I try to use the Promisify method I may be doing something wrong.
exports.makeRequest = function(someText){
return Promise.resolve(someText);
}
var makeRequestAsync = Promise.promisify(exports.makeRequest);
makeRequestAsync('Testing').then(function(data){
console.log(data); // --> log never appears
});
I really want to understand how promisify works.
I'm not able to make a simple example works on bluebird. I've used the new Promise method and it works, but when I try to use the Promisify method I may be doing something wrong.
exports.makeRequest = function(someText){
return Promise.resolve(someText);
}
var makeRequestAsync = Promise.promisify(exports.makeRequest);
makeRequestAsync('Testing').then(function(data){
console.log(data); // --> log never appears
});
I really want to understand how promisify works.
Share Improve this question asked May 8, 2015 at 5:01 Elvio CavalcanteElvio Cavalcante 5165 silver badges10 bronze badges 1-
1
You don't need to promisify it. Just call
makeRequest
, it already returns a resolved promise. – thefourtheye Commented May 8, 2015 at 5:02
1 Answer
Reset to default 7Bluebird's promisify()
only works with node-style functions that take a callback as their last argument where that callback takes two arguments, an error and the data. Your function does not meet this criteria.
You can read about how it works here.
In addition, there's no need to promisify a function that already returns a promise. You can just call that function directly and use its returned promise since it's already a promise returning function.
exports.makeRequest = function(someText){
return Promise.resolve(someText);
}
exports.makeRequest('Testing').then(function(data){
console.log(data);
});
Working demo: http://jsfiddle/jfriend00/n01zyqc6/
Of course, since your function isn't actually async, there doesn't appear to be any reason to even use promises with it at all.
Here's an example of actually promisifying something that is async and uses the right calling convention:
exports.myFunc = function(data, callback) {
// make the result async
setTimeout(function() {
// call the callback with the node style calling convention
callback(0, data);
}, 500);
};
var myFuncAsync = Promise.promisify(exports.myFunc);
myFuncAsync("Hello").then(function(result) {
console.log(result);
});