我怀疑这是 JS Promise 的一个功能,但我有一个 Promise 可以很好地解析,但仍然包含错误的数据(即,在不幸的地方出现空值)。如果存在空值,我希望错误的数据通过相同的 Promises 失败函数传递。
我想知道是否有办法让其自己的成功处理程序失败?
最佳答案
与然后
:
someAsyncTask()
.then(
data => {
if (!data) {
throw new Error('Bad data') // Or, return Promise.reject(...)
}
},
() => {
// If you need logic to handle when someAsyncTask rejects
// AND you want to continue to the next rejection handler,
// (in this case the catch), you'll need to either `throw`
// an error here or `return Promise.reject()`
}
)
.catch(
err => {
// err.name === 'Error'
// err.message === 'Bad data'
}
)
使用异步/等待
:
(async () => {
try {
const data = await someAsyncTask()
if (!data) {
throw new Error('Bad data')
}
} catch (err) {
// err.name === 'Error'
// err.message === 'Bad data'
}
})()
关于javascript - 你能让 Javascript Promise 的成功处理程序失败吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54899306/