javascript - 在 promise 中处理错误时返回成功

标签 javascript typescript vue.js promise

我有一个处理通过 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/

相关文章:

javascript - 如果不是通过单击更改复选框,如何使用 jQuery 进行监听?

javascript - 如何在 Node.js 中从数组中的值创建对象?

javascript - 当我尝试测试我的重试 util 函数时,jest.advanceTimersByTime 不起作用

javascript - 操作多个复选框选择代码如何工作?

vue.js - 是否可以从安装在 Vuejs 中发射?

javascript - jQuery json for 循环获取每个字符而不是项目数组

javascript - php数组没有出现在javascript中

typescript - 当 T 未定义时如何输入 `K extends keyof T`?

javascript - 替换后,跳过字符串的该部分 - Regex Javascript

vue.js - 访问 vuejs 中另一个组件中的模式