admin管理员组文章数量:1336660
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);
});
本文标签: javascriptI39m trying to use the Bluebird39s method Promisify and it39s not workingStack Overflow
版权声明:本文标题:javascript - I'm trying to use the Bluebird's method Promisify and it's not working - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742419777a2471423.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论