0%

javascript-promise-order-of-then-catch

What’s the difference of the following two code snippets?
first code snippet.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const handler = () => {
console.log("handler executed...");
};

const fetchData = async () =>
new Promise((resolve) => {
setTimeout(() => {
resolve("success in fetchData");
}, 100);
});

fetchData()
.then(handler)
.catch((error) => {
console.log(error);
});

second code snippet.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const handler = () => {
console.log("handler executed...");
};

const fetchData = async () =>
new Promise((resolve, reject) => {
setTimeout(() => {
reject("error in fetchData");
}, 100);
});

fetchData()
.catch((error) => {
console.log(error);
})
.then(handler);

The first code snippet is xxx.then().catch() while the second code snippet is xxx.catch().then(), since promise.catch also return a promise, so handler in the second code snippet will always be executed. But in the first code snippet, the handler will not be executed.

outputs:

first code snippet.

1
error in fetchData

second code snippet.

1
2
error in fetchData
handler executed...