【发布时间】:2015-11-10 23:08:58
【问题描述】:
似乎如果用于创建承诺的函数中没有引用“解决”函数,则该承诺是未定义的。在下面的代码中,...
var count = 0;
var limit = 3;
//
var thePromise;
function timeout(_count) {
thePromise.resolve(_count);
}
function sendMessage() {
return new Promise(function(resolve, reject) {
if (++count > limit) {
reject({'Limit Exceeded': count});
}
else {
// With this line in place, the return value from this function
// (expected to be a promise) is undefined
setTimeout(timeout.bind(null, count), 1000);
// If the line above is replaced by this, it works as expected
// setTimeout(/*timeout.bind(null, count)*/function (_count) {
// resolve(_count);
// }.bind(null, count), 1000);
}
});
}
function sendAnother(_count) {
console.log('Resolved with count %j', _count);
return sendMessage();
}
function detectError(_error) {
console.log('Rejected with %s', JSON.stringify(_error));
process.exit(1);
}
thePromise = sendMessage();
thePromise = thePromise.then(function (_count) { return sendAnother(_count)}, function(_error) {detectError(_error)});
尝试在创建承诺的函数之外进行解析,结果:
node-promises.js:6
thePromise.resolve(_count);
^
TypeError: undefined is not a function
at timeout (node-promises.js:6:16)
at Timer.listOnTimeout (timers.js:110:15)
但是如果第 16 行被注释掉并且第 18-20 行被取消注释,输出是:
Resolved with count 1
.. 这是我所期望的。我错过了什么?这是在 Windows 7 上使用 nodejs v0.12.2,如果这有什么不同的话。
【问题讨论】:
标签: javascript node.js promise