I read a lot of articles about promises. I know that promises are microtasks for task queue, async code executions are tasks. How does it happen in promises that after asynchronous code works synchronous code (i.e. after some fetch we can write synchronous code in then block, I guess in then block all code is asynchronous even if it banal console.log, for example)?
1 Answers
Per the promise specification, a .then()
or .catch()
handler is always called asynchronously after the current thread of execution finishes, even if the promise is already resolved. This is just part of a promise implementation to assure that that happens.
So, even in this example where the promise is already resolved, you will see in the console:
A
C
B
console.log("A");
Promise.resolve().then(() => {
console.log("B");
});
console.log("C");
How does it happen in promises that after asynchronous code works synchronous code (i.e. after some fetch we can write synchronous code in then block, I guess in then block all code is asynchronous even if it banal console.log, for example)? It contradicts the principles of async programming.
You can put any code you want in a .then()
block. It can be asynchronous code or synchronous code. It's just code. The code gets run at some point in the future when the .then()
handler gets called. It's similar to how you can put any code you want in a setTimeout()
callback. The timer controls when the code starts to run, but controls nothing else about the code.

- 683,504
- 96
- 985
- 979
-
It calls async but the code in then block can be sync – SerJernaut Jun 13 '20 at 17:43
-
@SerJernaut - Your code in a `.then()` handler can be any code you want, synchronous or asynchronous. But, it is always initiated asynchronously (on a future tick of the event queue). See the example I added to my answer. – jfriend00 Jun 13 '20 at 17:44