我有一个处理通过 Web API 执行的 HTTP 请求的 promise :
promise = promise.then(r => {
// ...
}, error => {
if (error.status == 404) {
// Here I can fix an error and continue properly
} else {
// Here the error should be propagated further in the promise
}
}
// later in the code:
promise.catch(r => { /* More error handling */ } );
在代码的后面,这个 promise 链接到更多的错误检查。
在出现 404 错误的情况下,我实际上可以“修复”问题,并且我不希望触发其他处理程序。在这种情况下,我宁愿让 promise 成功。我该怎么做?
更多代码来更深入地解释我的案例:
refresh() {
this.refreshAsync().catch(r => {
// Show error to the user.
notifications.showError("Unexpected error happened");
});
}
async refreshAsync() {
// Here goes a lot of vue-resource calls to gather the necessary data for a view. They are chained with `await`. Only one of them:
await this.$http.get(url).then(r => {
this.data = r.data;
}, error => {
// 404 is actually a legit response for API to return, so the user notification above should not be shown
if (error.status == 404) {
// handle successfully
} else {
// propagate an error, so the handler above could show a warning to the user.
}
});
}
最佳答案
你可以简单地返回一个拒绝/解决
if(error.status == 404)
return Promise.resolve('OK')
else
return Promise.reject('fail')
我做了一个例子来展示它是如何工作的, 仅针对这种情况:
httpRequest = function () {
return new Promise(function (res, rej) {
let status = (Math.round(Math.random()) === 1) ? 200 : 404;
console.log(status)
if (status === 200)
return res({ status })
else
return rej({ status })
})
}
let promise =
httpRequest()
.then(res => Promise.resolve('success'))
.catch(e => {
if (e.status === 404)
return Promise.resolve('success')
else
return Promise.reject('failed')
})
promise
.then(res => {
console.log(res)
})
.catch(e => {
console.log('this should not happen')
})
关于javascript - 在 promise 中处理错误时返回成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52831101/