什么是 UnhandledPromiseRejectionWarning: 错误?

What is UnhandledPromiseRejectionWarning: Error?

我粘贴了两个几乎相同的代码,只有一点点不同,一个工作正常但另一个给出 UnhandledPromiseRejectionWarning.

async function promise () {
  return new Promise((resolve, reject) => {
    throw new Error();
    resolve();
    reject();
  })
}

promise().then((data) =>{console.log('then')}).catch((err)=>{console.log('from the catch')});

输出为:

> node index.js
from the catch

但对于这种情况

function promise () {
  return new Promise(async (resolve, reject) => {
    throw new Error();
    resolve();
    reject();
  })
}

promise().then((data) =>{console.log('then')}).catch((err)=>{console.log('err')});

输出是这样的

> node index.js
(node:98195) UnhandledPromiseRejectionWarning: Error
    at /home/parthiv/Projects/exp/index.js:47:11
    at new Promise (<anonymous>)
    at promise (/home/parthiv/Projects/exp/index.js:46:10)
    at Object.<anonymous> (/home/parthiv/Projects/exp/index.js:53:1)
    at Module._compile (internal/modules/cjs/loader.js:1085:14)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
    at Module.load (internal/modules/cjs/loader.js:950:32)
    at Function.Module._load (internal/modules/cjs/loader.js:790:12)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)
    at internal/main/run_main_module.js:17:47
(Use `node --trace-warnings ...` to show where the warning was created)
(node:98195) 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: 1)
(node:98195) [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.

有人可以解释 promise 中异步函数的这种行为吗?

您已将 async 函数传递给 Promise 构造函数,这不是正确的做法。 async 函数的 return 值是未处理的值。

Promise 构造函数专为同步使用而设计,它完全无视其 return 值。如果你在函数中 throw 传递给一个 Promise 构造函数,Promise 构造函数将 return 一个被拒绝的 promise;这就是您在第一个示例中看到的行为。如果函数 return 是一个值,即使是一个 Promise,也没关系:the value is discarded.

About the executor, it’s important to understand the following:

  • The executor return value is ignored.
  • If an error is thrown in the executor, the promise is rejected.

async 函数将其 returnthrow 调用转换为 Promise 解析,但 async 函数 always return 一个承诺。因此,在您的第二个示例中,您的 throw 导致 Promise 被拒绝, 然后未处理 ; return 值如上所示被完全丢弃。如果不是 UnhandledPromiseRejectionWarning,您的 throw new Error() 将不会出现任何症状,您的 promise() returned 的承诺将永远无法解决。

如果你想要 promise() 到 return 一个承诺,你可以 return 内部 async 函数的 return 值,或者(甚至更好)使 promise() 本身成为一个异步函数。如果你确实需要 resolve/reject 调用,你总是可以从函数内部 return new Promise() ;每当 async 函数或 .then() 处理程序 return 是一个 Promise,return 值就会被解包。