gpt4 book ai didi

javascript - 链式 promise 不会捕获错误

转载 作者:行者123 更新时间:2023-12-01 02:11:17 30 4
gpt4 key购买 nike

我正在努力兑现 promise ,到目前为止我偶然发现了这一点:

new Promise((resolve, reject) => {
setTimeout(() => {
return resolve()
}, 400)
}).then(new Promise((resolve, reject) => {
setTimeout(() => {
return reject('some error')
}, 100)
})).then(() => {
console.log('All promises resolved')
}).catch((err) => {
console.log('Error: ' + err)
})

我的理解是,这个示例应该显示 Error: some error,第一个 promise 成功解决,第二个 promise 抛出错误。但是当我运行这个(在节点 9.7 中,如果这很重要)时,我收到此错误:

(node:10102) UnhandledPromiseRejectionWarning: some error
(node:10102) 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(). (rejection id: 1)
(node:10102) [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.
All promises resolved

我的.catch()似乎不起作用,是不是有问题?

最佳答案

您实际上传递的是 promise ,而不是函数。

你应该这样编写代码:

new Promise((resolve, reject) => {
setTimeout(() => {
resolve()
}, 400)
}).then(() => new Promise((resolve, reject) => {
setTimeout(() => {
reject(new Error('some error'))
}, 100)
})).then(() => {
console.log('All promises resolved')
}).catch((err) => {
console.log('Error: ' + err)
})

关于javascript - 链式 promise 不会捕获错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49753723/

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