【问题标题】:Promise chain of catchs承诺链捕获
【发布时间】:2021-11-06 22:22:28
【问题描述】:

我有这种情况:

controller.ts

methodA(): void {
    myServive.someMethod()
    .then( () => console.log("then") )
    .catch( e => {
        console.log("catch");
    });
}

service.ts

someMethod(): ng:IPromise<void> {

    const deferred = this.$q.defer<void>();

    return this.OtherService.otherMethod()
    .catch ( e => {
        deferred.reject(reason);
    }
}

其他服务.ts

otherMethod(): ng.IPromise<any> {
    return this.HttpService.get(url);
}

测试:

  • otherMethod (otherService.ts) 收到来自 HttpService 的错误。
  • someMethod (service.ts) 中的 catch 已执行。

为什么在controller.ts中,then块被执行了?

【问题讨论】:

  • 来自MDN:“如果 onRejected 抛出错误或返回本身被拒绝的 Promise,则 catch() 返回的 Promise 被拒绝;否则,它被解决。”

标签: javascript angularjs promise


【解决方案1】:

为什么,在controller.ts中,then块被执行了?

因为您发现了错误并在service.ts 中返回了 undefined

如果您不打算在其中处理任何错误,您似乎应该完全摆脱 service.ts 中的 catch/defer。

编辑:如果您希望在控制器中处理捕获,那么只需从 service.ts 中删除所有内容,然后就可以了:

// service.ts
someMethod(): ng:IPromise<void> {
    return this.OtherService.otherMethod()
}

如果您想在控制器中处理service.ts AND 中的捕获,则重新抛出错误(或新错误):

// service.ts
someMethod(): ng:IPromise<void> {

    const deferred = this.$q.defer<void>();

    return this.OtherService.otherMethod()
    .catch ( e => {
        // you can either do:
        // throw e
        // which rethrows the same error (same as not having a catch in here at all)
        // or you can handle the error and throw a new one like:
        //
        // ...some error handling code
        // throw new Error('my new error');
    });
}

无论您选择哪个,都不需要延期。

【讨论】:

  • 亚当,怎么解决?我们应该放“return deferred.reject(reason)”吗?
  • @LucianoBorges 解决什么问题?你想发生什么?
【解决方案2】:

如果之前的then(或catch)抛出错误,则会执行catch。如果没有错误,代码将执行下一条then 语句。

所以你有这个代码:

methodA(): void {
    myServive.someMethod()
    .then( () => console.log("then") )
    .catch( e => {
        console.log("catch"); // No errors thrown, so the code will continue in the next then
    });
}

所以你可以在catch 中抛出一个错误。代码会继续下一个catch:

methodA(): void {
    myServive.someMethod()
    .then( () => console.log("then") )
    .catch( e => {
        console.log("catch");
        throw new Error(e) // Some error happened! The code will continue in the next catch
    });
}

【讨论】:

  • Tks 罗生门! throw 应该在 service.ts 中,对吧?因此,我可以在 controller.ts 上执行 catch 块。我说的对吗?
  • 是的。或者您可以删除整个捕获。对于每个抛出的错误,将执行一个 catch
猜你喜欢
  • 2017-02-05
  • 2017-11-24
  • 2014-11-22
  • 1970-01-01
  • 2021-11-15
  • 2016-06-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多