P粉7703754502023-08-17 16:48:21
In addition to Nicholas' answer, you may be stuck by the repeated use of the identifier 'res'. The first use of a Promise internally is as a callback function, which returns the value 2 to the Promise. The second use in the last line is in a different scope and is used as a parameter name for the outer Promise's .then() method. It might help if you replace 'res' in the last line with 'outerPromiseResult', to clarify things.
P粉4935341052023-08-17 15:42:59
In short, it's because of the order in which you call .then
.
new Promise((resolve) => { new Promise((res) => { console.log("c"); resolve(3); res(2);
In the above code, we enter the external constructor, which immediately calls the external function. Then create an internal Promise and call the internal function. The inner function records "c", then resolves the outer Promise to 3, then resolves the inner Promise to 2.
So at this point we have 2 resolved Promises, but no code trying to use them.
}).then((response) => console.log(response))
After completing the construction of the inner Promise, we call .then
on the inner Promise. Since the Promise has resolved, this queues a microtask to run.
}).then((res) => console.log(res));
After completing the construction of the external Promise, we call .then
on the external Promise. Since the Promise has resolved, this queues a microtask to run.
Now we have finished running all the synchronous code. The call stack is empty and the microtask starts running. These are executed in first-in, first-out order, so the microtasks related to the inner Promise run first, record 2. Then run the remaining microtasks and record 3.