console.log('1');
await get()
.then()
.catch(() => {
console.log('2');
return;
});
console.log('3');
Why did console logs 1 2 3? I thought after return statement, the code will be not executed?
return
will only terminate the current function. Here, the function that gets terminated by the return
is the .catch
callback.
Since .catch
returns a resolved Promise, the await
ed Promise chain will resolve when the catch
resolves.
If you want to stop the outer function when the catch
runs, have your catch
return something that you check outside, eg:
(async() => {
console.log('1');
const result = await Promise.reject()
.catch(() => {
console.log('2');
return 2;
});
if (result === 2) {
return;
}
console.log('3');
})();
Or have the .catch
throw an error, so that the outer Promise chain rejects. Since it's being await
ed, the whole outer Promise will then reject:
const fn = async () => {
console.log('1');
const result = await Promise.reject()
.catch(() => {
console.log('2');
throw new Error();
});
console.log('3');
};
fn()
.then(() => console.log('resolved'))
.catch(() => console.log('rejected'))
If your .catch
doesn't do anything substantial but you want this sort of behavior, it's usually a good idea to omit it entirely. That way, when there's an error, the await
ed Promise will reject, the function will terminate, and the error can be caught by the appropriate consumer.
const fn = async () => {
console.log('1');
const result = await Promise.reject();
console.log('3');
};
fn()
.then(() => console.log('resolved'))
.catch(() => console.log('rejected'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With