Reputation: 59
I know that there is a message-queue and that JavaScript is single-threaded. And there's also an event-loop, taking messages from the queue and doing some work.
When you create a promise, and this promise is being kept in the message queue, when or how does the loop know when it's resolved (or rejected). Is it permanently asking, if the status is not "pending" or is the promise itself queuing to the message-queue when it is resolved or rejected?
After some research, I think I got it wrong. It is not the promise itself but the XHR-request that is actually blocking and running in its own thread to not block the main execution thread. So only the main execution thread is single-threaded and the XHR-thread will queue the callbacks to the main-thread when the XHR request gets a result (or fails).
So, corresponding to this article, is the promise itself being kept in the stack and will push the callback function to the queue when it is settled?
Upvotes: 4
Views: 1527
Reputation: 8297
So, corresponding to this article, is the promise itself being kept in the stack and will push the callback function to the queue when it is settled?
The following quotation comes from the Related article on microtasks suggested by nem035:
Once a promise settles, or if it has already settled, it queues a microtask for its reactionary callbacks. This ensures promise callbacks are async even if the promise has already settled. 1
Try going through the animated step-by-step diagrams,
After the seventh step it reaches this point:
So one can conclude that the promise itself is not kept in the stack, but the Promise then (callback) is added to the queue of Microtasks, which are processed after the stack becomes empty.
1https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/
Upvotes: 2
Reputation:
I know that there is a message-queue and that JavaScript is single-threaded. And there's also an event-loop, taking messages from the queue and doing some work.
When you create a promise, and this promise is being kept in the message queue, when or how does the loop know when it's resolved (or rejected). Is it permanently asking, if the status is not "pending" or is the promise itself queuing to the message-queue when it is resolved or rejected?
Promise are not "kept in the message queue", which contains only micro-tasks. The event loop knows nothing about promises. It merely picks micro-tasks off the queue for execution.
When a promise fulfills or rejects, the promise library puts tasks onto the queue for all the attached then
or catch
handlers. (If a then
or catch
handler is attached after the promise fulfills or rejects, then the task is put on the queue immediately.)
Upvotes: 0
Reputation: 664307
The promise will schedule the relevant function calls on the queue when it is getting resolved.
There is no polling involved, that would be pretty inefficient.
Upvotes: 1