Understanding the working of callbacks and promises in JavaScript
Tags: javascript, react, webdev, beginners
Published: 2022-10-30 18:22:50

Before we begin, try to figure out the output for the following code-piece
`let promiseObj = new Promise(
    function(resolve, reject) { resolve(1) }
 );
promiseObj.then((resolve) => { console.log(1) } );
console.log('a');
setTimeout(() => { console.log('h') }, 0);
console.log('b');
`

## **Understanding through an analogy**
If you are an Indian or know about India, you obviously know about the reservation system (priority) in India. For now let us consider 3 entities for our explanation.

1. The Government
2. Person belonging to some reserved category (Person A)
3. Person belonging to the GM category (Person B)

The Government of India has it's own set of tasks to be completed, which it performs for the upbringing of the nation. Let's consider both Person A and B, have some queries and tasks which the government must perform to keep them satisfied.

**Let's see the 3 entities in action!**

The Government starts performing it's own task, starting from time - **t0**. Person B wants the government to perform some tasks, so they go to the government at time - **t1** and put forth their queries, the govt. accepts their request and tells them-

> Don't worry I will perform the task which you requested, but not now, once I'm done with my tasks, I will take up yours.

Hearing this Person B returns happily. After a while Person A wants some tasks to be performed so they go to the govt. and put forth their query at time - **t2**. The govt. tells the same thing to Person A and the person returns happily.

Now the govt. is done with it's tasks and now it has to perform the tasks of the people. Now anyone would assume that the govt will take up the task of Person B since they were the one's that approached the govt. first. But NO!

**Now the twist!**

The Government instead of taking up the task of Person B takes up the task of Person A!!. Why?
Because Person A has more priority according to the reservation system, so govt. performs Person A's tasks first and then Person B's.

## **Decoding the analogy!**

Here **"The government's tasks"** represents **synchronous code** in javascript. **Person A's tasks** represents **callbacks** and **Person B's tasks** represents **promises** in javascript.

Javascript has many queues, which it uses along with event-loop to handle asynchronous code (We'll get to 2 such queues below) . Now that we know promises are handled before callbacks, let us now understand and find the output for the above code-piece

`let promiseObj = new Promise(
  function(resolve, reject) { resolve(1) }
);
promiseObj.then((resolve) => { console.log(1) } );
console.log('a');setTimeout(() => { console.log('h') }, 0);
console.log('b');`

JS first parses the whole code and executes the synchronous code first, which include

`console.log('a') //Line number 4
console.log('b') //Line number 7
Output
a 
b`

Later on it shifts it's attention to the promises and callbacks.

Note:- setTimeout is not part of javascript, it is part of the web api which is provided by the browser. setTimeout maps to an API called Timer present in the browser.

In line number 1 we are creating a promise using the new keyword which returns a promise object, which we are storing inside a variable called promiseObj. The promise object returned has many properties, one of them include `.then()`.
.then() is used to define a function which should be executed once the promise is resolved. So in our above example we are defining a function (line number 4) which just console logs 1 inside the .then().

`promiseObj.then((resolve) => { console.log(1) } );`

This above function which we have declared is pushed into the **JOB QUEUE**.

In setTimeout we explicitly specify the function to be auto-run or callled (callback function) when the time interval specified is over. Even though the time interval that we have specified is 0 the function gets pushed to the **CALLBACK QUEUE**.

![entities involved in the handling of async code](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3lutswnvyk4gjb7dz01j.png)

Now all the synchronous code is done executing, now the event-loop looks for the Job Queue first. Why? Because Job queue is given more priority (just like Person A). So we have our function present inside the job queue executed first, which console logs 1.

`Output
a
b
1`

Once all the functions present inside the job queue is executed, event-loop only now checks for the callback queue. In our example callback queue contains a function which was passed as a callback to the setTimer function.

`() => { console.log('h') }, 0`

Hence 'h' is logged at the very end.

`Output
a //sync
b //sync
1 //promise
h //callback`

## **Summary**
In JS all the synchronous code gets executed first.
ES6 has 2 queues

1. Job queue
2. Callback queue

Job queue has more priority than callback queue
All promises related functionality is pushed to job-queue and all callbacks are pushed to callback-queue.

**(If you find this article helpful please do support by sharing this article with those who might benefit from it. Thanks)**