gpt4 book ai didi

javascript - 尽管获得了 promise ,但未处理的 promise 拒绝

转载 作者:行者123 更新时间:2023-12-01 15:55:56 26 4
gpt4 key购买 nike

我不明白...是我还是 Node 中的错误?

正如预期的那样,这很好:

const a = new Promise((resolve, reject) => {
setTimeout(() => reject('timeout'), 1000);
});
a.catch(console.log);

这是发出警告:
const a = new Promise((resolve, reject) => {
setTimeout(() => reject('timeout'), 1000);
});
a.then(console.log);
a.catch(console.log);

我明白了
timeout
(node:40463) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): timeout
(node:40463) [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.

最佳答案

使用 .then(...) with a promise 返回一个新的 promise(称为 chaining )。因此,当您执行以下操作时:

a.then(console.log); // line 1 creates a new promise "b"
a.catch(console.log); // line 2 handles rejection on promise "a"

在哪里 a是您最初的 promise ,您正在第 1 行创建一个新的 promise (不再是 a。让我们称之为 b )。所以即使你使用 .catch(...)a ,您没有处理 b 上的拒绝,它解释了您在控制台上看到的消息。

为避免此消息,您应添加 .catch(...)对这个新的 promise b ,在第 1 行

关于javascript - 尽管获得了 promise ,但未处理的 promise 拒绝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52409326/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com