【问题标题】:Promise do not bubble outside承诺不在外面冒泡
【发布时间】:2017-09-05 05:25:45
【问题描述】:

我需要使用 Mocha 测试函数 testMe。但是当我的单元测试抛出错误时就会出现问题。这是一个简化的例子

function testMe(callback) {
    new Promise((resolve, reject) => {
        setTimeout(() => resolve([1,2,3]), 1000);
    }).then((result) => {
        callback(null, result);
    }).catch((error) => {
        callback(error, null)
    });
}

testMe((err, result) => {
   if(err) throw new Error();
   if(result.length < 5) throw new Error();
});

在这个例子中,在 throw 运行 catch 块之后。但我只需要在拒绝后运行 catch 块。

编辑:

在这种情况下,脚本永远不会停止。我不明白为什么。

function testMe(callback) {
    new Promise((resolve, reject) => {
        setTimeout(() => resolve([1,2,3]), 1000);
    }).then((result) => {
        callback(null, result);
    }, (error) => {
        callback(error, null)
    }).catch(() => {
        console.log('Do not throw an error but still running');
    });
}

testMe((err, result) => {
   if(err) throw new Error();
   if(result.length < 5) throw new Error();
});

【问题讨论】:

  • 在使用 Promise 时不要使用回调参数!
  • 但我需要使用它。因为在 testMe 中我使用的是 horseman API。
  • Use .then(…, …) instead of .then(…).catch(…) 避免调用callback 两次,尽管这仍然不会让你例外;只是未经处理的拒绝。
  • 不,您不需要将回调传递给testMe - 您应该有testMe return 一个承诺,然后用 mocha 进行检查。跨度>
  • 如果我使用 .then(..., ...) 而不是 .then().catch() 我收到 UnhandledPromiseRejectionWarning: Unhandled Promise RejectionWarning: Unhandled Promise Rejection (rejection id: 1): Error

标签: javascript node.js callback promise mocha.js


【解决方案1】:

你可以直接return the promise from the test:

function testMe() {
//             ^^ drop the callback
    return new Promise((resolve, reject) => {
//  ^^^^^^ return the promise
        setTimeout(() => resolve([1,2,3]), 1000);
    });
}

var p = testMe().then(result) => {
//              ^^^^^ use the promise
   if(result.length < 5) throw new Error();
});
return p; // to mocha

【讨论】:

    【解决方案2】:

    当您使用 Promise 时,请从函数中返回 Promise,而不是使用回调。

    例如,而不是:

    function testMe(callback) {
        new Promise((resolve, reject) => {
            // ...
        });
    }
    

    使用:

    function testMe(callback) {
        return new Promise((resolve, reject) => {
            // ...
        });
    }
    

    这样你就可以得到函数调用者的承诺。

    如果您需要混合使用这两种样式,即返回 Promise 和接受回调,请考虑使用可靠的库来为您处理,尤其是在您自己编写这些样式之间的转换时遇到困难时:

    【讨论】:

    • 但是我有普通的摩卡测试,不等待承诺。
    • 在我的情况下如何使用这些库?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-20
    • 1970-01-01
    • 1970-01-01
    • 2017-05-18
    • 2016-09-18
    • 1970-01-01
    • 2012-04-25
    相关资源
    最近更新 更多