I learned from the following article that Promise in JavaScript is called synchronously.
I assumed that functions passed to Promise were asynchronous functions.
Below is a summary of the Promise call order for your own use.
Promise Calling Order Summary
Functions passed to Promise are executed immediately upon Promise creation
console.log("start"); new Promise((resolve, reject) => { console.log("1"); }); new Promise(async (resolve, reject) => { console.log("2"); }); console.log("end");
The async function is also executed immediately.
result
start 1 2 end
then() is an asynchronous function, and resolve() is a function that registers then() in the task queue
console.log("start"); new Promise((resolve, reject) => { console.log("1"); resolve(null); // regist then() console.log("2"); }).then(() => { console.log("3"); }); new Promise((resolve, reject) => { console.log("4"); }).then(() => { console.log("5"); }); console.log("end");
The second then() is not registered in the task queue, so "5" is not displayed.
result
start 1 2 4 end 3
The same goes for the relationship between reject() and catch()
The reject() does not immediately call catch(). catch() is registered by reject() and is called asynchronously.
console.log("start"); new Promise((resolve, reject) => { console.log("1"); reject(null); // regist reject() console.log("2"); }).catch(() => { console.log("3"); }); console.log("end");
result
start 1 2 end 3
Impressions, etc.
I am ashamed to admit that I mistakenly thought that the function passed to Promise was an asynchronous function and that then() was immediately executed on resolve().
So I was wondering, "What's the point of writing code after resolve()?" I've been bothered by this for a long time, but I see that it is registered asynchronously at the time of the resolve() call. I finally got it straightened out.