Reputation: 85
I have a DB query call e.g. getUserByIdOrThrow(id: number): User
;
How can I properly handle possible promise rejection after getUserByIdOrThrow
call?
In case of an error, I need to ignore it completely, but if promise resolved successfully, I need to call another async function.
Example flow:
DBCallAsync
/ \
resolved rejected
/ \
another call do nothing
That how I tried to approach this problem (not working as I expected):
from(this.dbService.getUserByIdOrThrow(100)).pipe(
tap(({ phone }) => {
from(this.userService.sendMessage(phone, "hello")).pipe(
catchError((err) => {
// doesnt catches
return EMPTY;
}),
)
}),
catchError((err) => {
// doesnt catches
return EMPTY;
}));
How can I implement this in the right way?
Upvotes: 0
Views: 1743
Reputation: 6424
Since both functions return Promise I wouldn't recommend of using an Observable, you would be much better handling it in a Promise way:
try {
const { phone } = await this.dbService.getUserByIdOrThrow(100);
await this.userService.sendMessage(phone, "hello"))
} catch (error) {
}
Or using RXJS style if you are insist on using it (switchMap
operator is used for returning and flattaning an inner obsevable, in addition there's no need to use from
inside switchMap
since it can handle Promises)
from(this.dbService.getUserByIdOrThrow(100))
.pipe(
switchMap(({ phone }) => this.userService.sendMessage(phone, "hello")),
catchError((err) => EMPTY)
);
Upvotes: 2