I would like to show 2 cases and ask only about the second case.
Case1:
Promise.resolve(1)
.then((x) => console.log(1))
.catch((x) => console.log(2))
.then((x) => console.log(3));
Promise.reject(2)
.then((x) => console.log(4))
.then((x) => console.log(5))
.catch((x) => console.log(6))
.then((x) => console.log(7));
// 1 3 6 7
Its ok. this code produced the following sequence: 1 3 6 7
Case 2:
Promise.resolve(1)
.then((x) => console.log(1))
.catch((x) => console.log(2))
.then((x) => console.log(3));
Promise.reject(2)
.then((x) => console.log(4))
// .then((x) => console.log(5))
.catch((x) => console.log(6))
.then((x) => console.log(7));
// 1 6 3 7
This code produced the strange sequence: 1 6 3 7
Please tell me about the mechanism that temporarily stops the execution of the first promise.
Let's analyse the second snippet and give some names to the promises that are created:
Promise.resolve(1) // promise A
.then((x) => console.log(1)) // B
.catch((x) => console.log(2)) // C
.then((x) => console.log(3)); // D
Promise.reject(2) // E
.then((x) => console.log(4)) // F
.catch((x) => console.log(6)) // G
.then((x) => console.log(7)); // H
First the main, synchronous script executes as follows:
(x) => console.log(1)
and resolve BAt this moment the synchronous part ends: the callstack is empty. The engine will now process any jobs that might be waiting in its queues. The promise job queue has two entries, so execution will continue as follows:
The first job is pulled from the promise job queue and is executed in a first microtask:
(x) => console.log(1)
and resolve B
The next job is pulled from the promise job queue and is executed:
(x) => console.log(6)
and resolve GThe next job is pulled from the promise job queue and is executed:
(x) => console.log(3)
and resolve DThe next job is pulled from the promise job queue and is executed:
(x) => console.log(6)
and resolve G
(x) => console.log(7)
and resolve HThe next job is pulled from the promise job queue and is executed:
(x) => console.log(3)
and resolve DThe next job is pulled from the promise job queue and is executed:
(x) => console.log(7)
and resolve HThe promise job queue is now empty and the task ends.
And so it is expected that the output is 1, 6, 3, 7