【问题标题】:Why is 'new Promise(...)' returning 'undefined'?为什么'new Promise(...)'返回'未定义'?
【发布时间】: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


    【解决方案1】:

    因为这条线而发生:

    thePromise.resolve(_count);
    

    该对象上没有resolve 函数。 resolve 来自你在实例化新 promise 时创建的函数:

    return new Promise(function(resolve, reject) {
    

    通过注释掉该行并使用替代函数,您正在调用正确的resolve(),这会导致所需的输出。解决此问题的一种方法是将解析函数传递给您的超时调用,例如:

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

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


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

    【讨论】:

    • 感谢马特 - 您建议的更改使其按预期工作。我认为我出错的地方是期望 resolve() 函数存储在承诺中;但它似乎只在调用then()时定义。
    猜你喜欢
    • 2020-04-11
    • 1970-01-01
    • 2014-10-24
    • 2021-12-11
    • 2019-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多