Say we have functions A
and B
that return promises. B
should be called only in case A
rejects, and I need to log both success and error results of both promises. First, I came up with this piece of code:
const A = () => Promise.reject(true);
const B = () => Promise.resolve(true);
A()
.then(() => {
console.log('A success');
})
.catch(() => {
console.log('A error');
return B();
})
.then(() => {
console.log('B success');
})
.catch(() => {
console.log('B error');
});
It works fine in case A
rejects. In case A
resolves, however, I'm getting one additional B success
message, which is perfectly expected but which I do not need in this case.
One possible solution I came up with is attaching the .then()
for B()
right next to the B()
call.
const A = () => Promise.reject(true);
const B = () => Promise.resolve(true);
A()
.then(() => {
console.log('A success');
})
.catch(() => {
console.log('A error');
return B().then(() => {
console.log('B success');
});
})
.catch(() => {
console.log('B error');
});
This of course solves my problem but it feels like more of a hack than a solution. I believe there are better approaches and practices for composing this kind of promise chains.