【问题标题】:JS Promises - Why am I seeing the UnhandledPromiseRejectionWarning and DeprecationWarning?JS Promises - 为什么我看到 UnhandledPromiseRejectionWarning 和 DeprecationWarning?
【发布时间】:2018-04-27 21:14:58
【问题描述】:

我正在掌握 Promise 以及如何设置它们,但是我不明白为什么 node 认为我的 Promise 在涉及错误时未处理...有人可以解释一下吗?

我的简单代码

    // Setting up the Promise
    function add(x, y) {
        return new Promise((response, reject) => {
            // Simple conditional (not perfect, but it just proves a point)
            if(x !== null && y !== null) {
                // I know I could have done 'response(x + y)', but I wanted 
                // to console.log the result also
                var calc = x + y
                response(calc)
                console.log('Calculation: ' + x + ' + ' + y + ' = ' + calc)
            } else {
                // My console does not throw this error?
                reject('One of the inputs was null')
            }
        })
    }
    
    // Function using the Promise
    function calc() {
        add(1, 3)
            .then(res => add(res, 3))
            .then(res => add(res, null))
            .then(res => console.log('Final result: '+res))
            .catch(err => {
                // This error is thrown in console
                throw new Error('Something went horribly wrong')
            })
    }
    
    // Run the code
    calc();

更新

我最初发布了带有抛出错误的“拒绝”,我知道需要捕获该错误。

我还想了解为什么在我的控制台中看不到“拒绝”中的字符串?

控制台输出:

Calculation: 1 + 3 = 4
Calculation: 4 + 3 = 7
(node:61950) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): Error: Something went horribly wrong
(node:61950) [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.

【问题讨论】:

  • 如果你在catch 子句中抛出一个新错误,它将沿着承诺链传播。所以你需要第二个catch 来捕捉你在第一个catch 中抛出的错误。你可能只想在抛出它的时候返回reject子句中的字符串,因为你在reject中返回的内容将被用作catch中的错误。
  • 谢谢@Shilly - 我已经编辑了我的问题。我理解您对需要捕获的抛出错误的意思,但是如果我不抛出任何东西,而只有reject('some error message'),那又如何呢?我在控制台中没有看到错误消息?
  • @Shilly - 啊,我知道reject() 部分就像response() 部分一样,它需要在那个时候传递或调用一些东西。输入reject(console.log('Rejection message')) 失败时会打印到控制台,但是我仍然收到UnhandledPromiseRejectionWarning: Unhandled promise rejection
  • 您仍然在未处理的捕获中抛出错误。编辑后,catch 内的err 等于“其中一个输入为空”,因为这就是您拒绝承诺的原因。因此,如果您需要将这两件事都记录到控制台,只需将 catch 处理程序更改为 console.error( err ); console.error( 'Something went horribly wrong' ) 以便记录被拒绝的文本和 catch 内的文本。由于这是您最后一个 catch 处理程序,因此您希望在那里结束错误链。

标签: javascript node.js promise es6-promise


【解决方案1】:

在你的函数中使用 Promise :

// Function using the Promise
function calc() {
    add(1, 3)
        .then(res => add(res, 3))
        .then(res => add(res, null))
        .then(res => console.log('Final result: '+res))
        .catch(err => {
            // This error is thrown in console
    --->    throw new Error('Something went horribly wrong')
        })
}

使用---> 创建的行会引发错误。该错误没有被捕获。通常,当您发现错误时,您想对其进行处理。如果你把它扔回去或抛出另一个错误,应该捕获那个抛出。

我会做的如下:

// Function using the Promise
function calc() {
    return add(1, 3)
        .then(res => add(res, 3))
        .then(res => add(res, null))
        .then(res => console.log('Final result: '+res))
        .catch(err => {
            // This error is thrown in console
            throw new Error('Something went horribly wrong')
        })
}

calc().catch(err => {
    console.log(error.message); // For example
});

【讨论】:

  • 有什么方法可以使用reject() 部分,这样我就不必在calc() 的末尾加上catch()?我将行更改为 reject(console.log('some error') 并打印到控制台,但仍然出现弃用错误,但更改为 reject(new Error('some message')) 什么也没做...
  • 如果你使用reject(),你必须catch()那个拒绝。但是没有什么能阻止你只记录错误而不拒绝。
【解决方案2】:

你正在调用reject 并且抛出一个错误。您只需执行其中一项即可。

您没有显示第一条错误消息。

当您调用add 时,使用.catch 处理任何抛出的错误也很重要。

当你这样做时: throw new Error('Something went horribly wrong') 你仍然在promise 中,如果你没有抓住它,你就会造成问题。在 Node.js 的未来版本中,这将导致您的应用程序以错误代码退出。因此,您需要确保始终在 Promise 中捕获抛出的错误。

使用拒绝

// Setting up the Promise
function add(x, y) {
  return new Promise((response, reject) => {
    // Simple conditional (not perfect, but it just proves a point)
    if(x !== null && y !== null) {
      // I know I could have done 'response(x + y)', but I wanted 
      // to console.log the result also
      var calc = x + y
      response(calc)
      console.log('Calculation: ' + x + ' + ' + y + ' = ' + calc)
    } else {
      // My console does not throw this error?
      reject(new Error('One of the inputs was null'))
    }
  })
}

// Function using the Promise
function calc() {
  return add(1, 3)
    .then(res => add(res, 3))
    .then(res => add(res, null))
    .then(res => console.log('Final result: '+res))
    .catch(err => {
      console.error("Internal Error:", err.message);
      // This error is thrown in console
      throw new Error('Something went horribly wrong')
    })
}

// Run the code
calc().catch((err) => {
  console.error("Outer error:", err.message);
});

使用投掷:

// Setting up the Promise
function add(x, y) {
  return new Promise((response, reject) => {
    // Simple conditional (not perfect, but it just proves a point)
    if(x !== null && y !== null) {
      // I know I could have done 'response(x + y)', but I wanted 
      // to console.log the result also
      var calc = x + y
      response(calc)
      console.log('Calculation: ' + x + ' + ' + y + ' = ' + calc)
    } else {
      // My console does not throw this error?
      throw new Error('One of the inputs was null')
    }
  })
}

// Function using the Promise
function calc() {
  return add(1, 3)
    .then(res => add(res, 3))
    .then(res => add(res, null))
    .then(res => console.log('Final result: '+res))
    .catch(err => {
      console.error("Internal Error:", err.message);
      // This error is thrown in console
      throw new Error('Something went horribly wrong')
    })
}

// Run the code
calc().catch((err) => {
  console.error("Outer error:", err.message);
});

我在add 返回的promise 中添加了return,以便您可以catch 最终错误。

另一种方法是不抛出最终错误并以不同方式处理它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-24
    • 1970-01-01
    • 1970-01-01
    • 2023-01-09
    • 2021-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多