I have this scenario:
methodA(): void {
myServive.someMethod()
.then( () => console.log("then") )
.catch( e => {
console.log("catch");
});
}
someMethod(): ng:IPromise<void> {
const deferred = this.$q.defer<void>();
return this.OtherService.otherMethod()
.catch ( e => {
deferred.reject(reason);
}
}
otherMethod(): ng.IPromise<any> {
return this.HttpService.get(url);
}
Test:
Why, in the controller.ts, the then block is been executed?
The catch is executed if some previous then (or catch) throws an error. If no errors, the code will execute the next then statement.
So you have this code:
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
});
}
So you can throw an error inside the catch. The code will continue to the next 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
});
}
Why, in the controller.ts, the then block is been executed?
because you caught the error and returned undefined in service.ts
It looks like you should just get rid of the catch/defer entirely in service.ts if you don't plan on handling any errors in there.
EDIT: If you want the catch to be handled in the controller, then just remove all the stuff from service.ts and just let do:
// service.ts
someMethod(): ng:IPromise<void> {
return this.OtherService.otherMethod()
}
If you want to handle the catch in service.ts AND in the controller, then rethrow the error (or a new one):
// 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');
});
}
No matter which you choose, you don't need a deferred.