ES6 Promises is probably the topic that is the worst explained everywhere and always 🫣 .
Promise is an object✨, if you open web inspector, click the console and print :
You will see that it has actually 3 properties but we are interested in two:
- [[PromiseState]] - a state that has 3 states itself,
- and [[PromiseResult]].
Let's explain what [[PromiseState]] values are and what each one means.
- First one is fulfilled: it means that everything was completed successfully,
- Second one is rejected: an error occurred and it was rejected,
- and last one is pending: we are still waiting for a response, neither resolved nor rejected.
As for [[PromiseResult]], it has two states:
- undefined - when nothing has been returned yet.
- and the value that we pass to the either the resolved or rejected method as their argument.
Now let's explain how these conditions change. In the promise printed above, we put an arrow function that does nothing, however, the promise callback function is generally given two arguments, resolve and reject, which will be called depending on how successfully the callback function completed. Let's make it clearer so that we can write something like that
We will see that
PromiseState - is already fullfiled (even though it prints resolved in the console, it is a bug of the browser)
and PromiseResult: completed, similarly, if we returned rejected("reject"), the state would be: "rejected" and value: "reject" .
If we take a look into the Promise prototype, we will see 3 built-in methods:
- then() - which is called if the Promise is resolved,
- catch() - which is called if it is rejected,
- and finally() - which is always called, regardless of the return state. then() and catch() returns a Promise itself, which gave us possibility to pass another callback function , so it allows us to build a whole chain of promises.
Let's talk about where the promise goes in the event loop. As we know, the asynchronous calls that the browser sends first go to web api -> then the results goes in the queue -> and when the call stack finishes, they will return in sequence from the queue.
Queue- itself is divided into 2 types of queues,
- the first is the queue of macrotasks: setTimeOut, setInterval, setImmediate etc.
- the second is the queue of microtasks: process.nextTick, Promise callback, async functions, queueMicrotask...
When the stack is finished, first it returns microtasks and then the macrotasks are released from the queue. That is, the promise will always return from the queue earlier than setTimeOut 🤌.
Top comments (0)