gpt4 book ai didi

javascript - 如果 promise 被拒绝,如何正确抛出错误? (未处理的 promise 拒绝警告)

转载 作者:行者123 更新时间:2023-11-29 19:02:35 24 4
gpt4 key购买 nike

我有一个 promise ,如果 promise 被拒绝,我希望抛出一个异常。我试过这个:

var p = new Promise( (resolve, reject) => {
reject ("Error!");
} );

p.then(value => {console.log(value);});

但是我收到了 DeprecationWarning:

(node:44056) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): Error!
(node:44056) 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 被拒绝,抛出错误的正确方法是什么(以便程序以堆栈跟踪终止)?

我已经尝试在 catch 子句中插入 throw 语句,但这又像以前一样产生了 DeprecationWarning。事实上(经过一些阅读后)我明白在 catch 中抛出会产生对 reject 回调的另一个调用。

最佳答案

你可以捕获 unhandledRejection记录堆栈跟踪的事件,假设您使用适当的错误拒绝:

var p = new Promise( (resolve, reject) => {
reject( Error("Error!") );
} );

p.then(value => {console.log(value);});

process.on('unhandledRejection', e => {
console.error(e);
});

关于javascript - 如果 promise 被拒绝,如何正确抛出错误? (未处理的 promise 拒绝警告),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45771024/

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