打破承诺链

时间:2019-10-28 16:18:58

标签: javascript promise axios es6-promise bluebird

我正在使用axios响应拦截器,并且取消请求后,需要断开一个Promise链。我不想为我的应用程序中的所有请求添加已取消请求的错误检查。我已经尝试过bluebird,但似乎只是承诺取消,而不是断链。 我必须在第一个陷阱中处理错误。此图一般显示了该问题。然后,最新和捕获位于不同的文件中。

Promise
.then((response) => {

)
.catch((error) => {
  // break promise here
})
.then((response) => {
 // skip
 // I don't want any extra checks here!
)
.catch((error) => {
  // skip
  // I don't want any extra checks here!
})

2 个答案:

答案 0 :(得分:1)

另一种选择是抛出一个自定义错误,该错误可以在结尾的单个catch块中捕获,就像这样:

const errorHandler = require('path/to/handler')
class ProcessingError1 extends Error {
    constructor(message) {
        super(message);
        this.name = "ProcessingError1";
    }
}
class ProcessingError2 extends Error {
    constructor(message) {
        this.message = message;
        this.name = "ProcessingError2";
    }
}
const process1 = async () => {
    throw new ProcessingError1("Somethign went wrong");
};
const process2 = async () => {
    return { some: "process" };
};
const someApiCall = async () => ({ some: "response" });

someApiCall()
    .then(process1)
    .then(process2) // process2 is not run if process1 throws an error
    .catch(errorHandler);
// ErrorHandler.js

module.exports = e => {
        if (e instanceof ProcessingError1) {
            // handle error thrown from process1
        }
        else if (e instanceof ProcessingError2) {
            // handle error thrown from process2
        }
        else {
            // handle other errors as needed..
        }
    }

答案 1 :(得分:0)

最后只保留一个catch块即可收集您的诺言链触发的所有错误。

如果一个诺言在链中引发以下事件,则不会执行

Promise
.then((response) => {

)
.then((response) => {
 // skip
 // I don't want any extra checks here!
)
.catch((error) => {
  // skip
  // I don't want any extra checks here!
})