<分区>
设置
在为 Node 编写一些数字 Javascript 代码时,一个想法出现了,“为什么不让它异步呢?”例如,
var mySquare = function(x, callback) {
callback(null, x * x);
}
mySquare(3, function(err, res) { console.log(res); });
// prints 9
除非计算复杂得多,并且可能会引发错误。
问题
如何在不重写它以使用 promises 的情况下 promisify 这个函数?使用bluebird's promisify ,通过 var promisedSquare = Promise.promisify(mySquare)
,返回一个错误堆栈:
TypeError: undefined is not a function
at l (/path/bluebird.min.js:30:15474)
at Function.e.promisify (/path/bluebird.min.js:30:16031)
at repl:1:30
...
看起来 bluebird 似乎试图评估 mySquare
。我在 promise 像 d3.json
(包装 XHR)这样的库函数时没有遇到任何问题,所以我很困惑:除了回调驱动的异步函数之外,我还需要为 bluebird 提供任何东西吗?