Arc*_*heg 6 javascript promise typescript vue.js
我有一个承诺,处理通过Web API执行的HTTP请求:
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 */ } );
Run Code Online (Sandbox Code Playgroud)
在代码的后面,这个承诺被链接到更多的错误检查.
在404错误的情况下,我实际上可以"修复"一个问题,我不希望其他处理程序触发.在这种情况下,我宁愿让这个承诺成功.我怎样才能做到这一点?
更多代码可以更深入地解释我的案例:
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.
}
});
}
Run Code Online (Sandbox Code Playgroud)
您只需返回拒绝/解决即可
if(error.status == 404)
return Promise.resolve('OK')
else
return Promise.reject('fail')
Run Code Online (Sandbox Code Playgroud)
我做了一个例子来展示它是如何工作的,仅针对这种情况:
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')
})
Run Code Online (Sandbox Code Playgroud)