When I execute the following code, the block of code A gets executed before the block of code B.
return new Promise((resolve, reject) => {
try {
resolve()
} finally {
// block of code A
}
}).then(() => {
// block of code B
})
But I don't understand why A is executed first.
The resolution (or rejection) of a promise triggers the then
corresponding to it, so I would expect block of code B to be run before block of code A.
From the doc:
When either of these options (resolve/reject) happens, the associated handlers queued up by a promise's then method are called.
I also read this:
the executor is called before the Promise constructor even returns the created object
the executor = the function passed as param to the Promise object.
The latter quote makes me think that the try catch
can be finished before the resolution or rejection handlers are triggered (before the executor function is returned from the Promise). It would explain that the finally
is triggered before the Promise's then
.
HOWEVER, I tried making a call to an external API with fetch and await
ing for the response before continuing, hoping that the Promise function would widely have the time to return the executor function before the try catch
is finished:
return new Promise(async (resolve, reject) => {
try {
await fetch('https://swapi.co/api/people/1/')
resolve()
} finally {
// block of code A
}
}).then(() => {
// block of code B
})
And it turned out that A was still executed before B. I expected the resolution handler to be triggered before A is executed, since resolve
is called before A is executed. But I am wrong, and I don't understand why.
May someone explain me please?