【问题标题】:Why does the await call for my custom promise hang?为什么我的自定义承诺的 await 调用会挂起?
【发布时间】:2019-08-23 12:42:42
【问题描述】:

我正在尝试使用 Mocha 在我的 Express/Node 后端测试一个函数。我创建了一个由函数修改的实际参数的存根:它有一个在 getValue 中调用的send 方法(我要测试的函数)和一个ready 参数,当我初始化一个新的承诺时当在存根上调用 send 时,存根被创建并解析。

我正在尝试await 这个承诺,但它只是挂起(然后摩卡超时测试)。下面的 setTimeout 打印出Promise { 'abc' },我认为这意味着承诺已按预期解决,但等待永远不会完成。

这是测试文件中的相关代码:

function ResStubTemplate() {
        return {
                _json: undefined,
                _message: undefined,
                json: function(x) {
                        this._json = x;
                        return this;
                },
                send: function(message) {
                        this._message = message;
                        this.ready = Promise.resolve("abc");
                        return this;
                },
                ready: new Promise(_ => {})
        }
}

// This is the test
it("should get the value.", async function(done) {
        let req = { query: { groupId: 12345 } };
        res = ResStubTemplate();
        controller.getValue(req, res);
        setTimeout(() => console.log(res.ready), 1000); // prints Promise { 'abc' }
        let x = await res.ready; // hangs??
        console.log(x); // never prints
        done();
}

这是测试文件中的相关代码:

exports.getValue = function(req, res) {
        ValueModel.findOne({groupId: req.query.groupId})
           .then(value => res.json({value: value}).send();                                                                                                         
};                                                                                                    

我得到的错误是:

Error: Timeout of 5000ms exceeded. 
For async tests and hooks, ensure "done()" is called; if returning a Promise,
ensure it resolves. (/.../test/api/controller_test.js)

【问题讨论】:

  • new Promise(_ => {}) 这将永远无法解决。

标签: javascript node.js express async-await mocha.js


【解决方案1】:

当表达式:

let x = await res.ready; // hangs??

… 被评估,值是这段代码创建的承诺:

ready: new Promise(_ => {})

那个承诺从不解决,所以它一直在等待它。

稍后你会这样做:

 this.ready = Promise.resolve("abc");

... 用新的(已解决的)promise 替换该 promise,但 new promise 不是您正在等待的值。

【讨论】:

    猜你喜欢
    • 2017-07-23
    • 2017-12-05
    • 1970-01-01
    • 1970-01-01
    • 2021-04-23
    • 2016-06-08
    • 2018-09-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多