为什么'new Promise(…)'返回& # 39;未定义# 39;

Why is 'new Promise(...)' returning 'undefined'?

本文关键字:返回 未定义 new Promise 为什么      更新时间:2023-09-26

如果'resolve'函数在用于创建承诺的函数中没有被引用,那么承诺是未定义的。在下面的代码中,…

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,如果这有任何区别的话。

因为这一行:

thePromise.resolve(_count);

对象上没有resolve函数。resolve来自实例化新承诺时创建的函数:

return new Promise(function(resolve, reject) {

通过注释掉这行,并使用替代函数,您调用了正确的resolve(),从而产生所需的输出。解决这个问题的一个方法是将resolve函数传递到超时调用中,例如:

function timeout(resolve, _count) {
    resolve(_count);
}

虽然我不确定你为什么要这样做。


你的标题问为什么new Promise返回未定义,当事实是,它不是。它确实返回了一个有效的承诺。只是resolve不是promise对象上的有效函数。