我正在努力使承诺有效,到目前为止,我偶然发现了这一点:
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
,第一个承诺成功解决,第二个承担错误。但是当我运行它时(在节点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()
似乎没有用,它有问题吗?
答案 0 :(得分:2)
你实际上是在传递承诺,而不是功能。
您应该像这样编写代码:
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)
})