【问题标题】:UnhandledPromiseRejectionWarning while using assert.doesNotReject使用 assert.doesNotReject 时出现 UnhandledPromiseRejectionWarning
【发布时间】:2021-08-05 23:50:13
【问题描述】:
const assert = require('assert');

main = () => {
    try {
        const toTest = async () => {
            return Promise.reject('ERROR'); // or throw 'Error';
        }
        assert.doesNotReject(toTest, TypeError);
    } catch (e) {
        console.log(e);
    }
}

main();

复制到文件后运行。它提示出来

(node:3056) UnhandledPromiseRejectionWarning: ERROR
(Use `node --trace-warnings ...` to show where the warning was created)
(node:3056) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:3056) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

它只是给出警告。有任何解决这个问题的方法吗?谢谢

【问题讨论】:

    标签: javascript node.js asynchronous promise assert


    【解决方案1】:

    这是因为从 Node v7 开始,如果您不处理被拒绝的承诺,您将收到 UnhandledPromiseRejectionWarning 警告。 预计您使用.catch(...) 处理所有承诺拒绝,或者如果您使用async/await,则使用try...catch 块处理它。 这是为了确保您不会忽略代码中发生的任何错误,在未来的 Node 版本中,此警告实际上是一个错误。

    您的代码发出此警告是因为 toTest 正在返回一个 Promise 拒绝,但它没有得到处理。
    当您调用 assert.doesNotReject(toTest, TypeError); 时,它会等待 toTest 承诺并检查承诺是否未被拒绝。 由于等待的承诺返回一个拒绝,断言将捕获它并再次拒绝它,并且由于拒绝的承诺没有被处理,它会给出一个警告说UnhandledPromiseRejectionWarning

    使用 assert.doesNotReject() 实际上没有用,因为捕获拒绝然后再次拒绝几乎没有什么好处。

    来源:https://nodejs.org/api/assert.html#assert_assert_doesnotreject_asyncfn_error_message

    【讨论】:

    • toTest() 返回一个拒绝并且不被处理,但是 assert.doesNotReject() 由于测试目的应该提供一个被拒绝的承诺
    • 那是因为assert.doesNotReject 捕捉到拒绝并再次拒绝它。让我用这些信息更新答案
    【解决方案2】:

    我发现 assert.doesNotReject 返回一个承诺 所以不是'assert.doesNotReject(...)',它应该是'await assert.doesNotReject(...)'

    【讨论】:

      猜你喜欢
      • 2019-08-17
      • 2019-04-26
      • 2019-03-11
      • 1970-01-01
      • 1970-01-01
      • 2020-06-19
      • 1970-01-01
      • 2017-09-16
      • 1970-01-01
      相关资源
      最近更新 更多