Event Loop, Callbacks & Promises
Tags: javascript, webdev, codenewbie, beginners
Published: 2021-01-11 07:04:11

In this new article related to JavaScript you'll learn about **Event Loops**, **Callbacks** and **Promises**. 

---

## Event Loop

The browser uses a concept called the event loop to handle concurrency or parallel events. 

JavaScript can only execute one statement at a time. it needs the event loop to informed of when to execute which specific statement. 

The event loop handles this with the concepts of a stack and a queue. 

#### Synchronous Code: 

Which does not use any asynchronous web API will get executed in a synchronous manner. 

```javascript
// Example Function

function one() {
    console.log(`one`); 
}

function two() {
    console.log(`two`); 
}

function three() {
    console.log(`three`); 
}

// call these function

one(); 
two(); 
three(); 

//Output- one, two, three
```

The event loop handles this with the concepts of a stack. 

**Pseudocode** : 

- Add `one()` to the stack, run one `one()` which logs 'three' to the console, remove one() from the stack. 
- Add two()` to the stack, run two()` which logs 'two' to the console, remove two() from the stack.
- Add three()` to the stack, run one` `three()` which logs 'three' to the console, remove three() from the stack.

---

#### Asynchronous Code

Which uses asynchronous code web API will get executed in Asynchronous manner. In general, however, asynchronous requests should be preferred over synchronous requests for performance reasons. 

```js
// Example Function

function one() {
    console.log(`one`); 
}

function two() {
    setTimeout(() => {
        console.log(`two`);        
       }, 0)
    }

function three() {
    console.log(`three`); 
}


// call these function
one(); 
two(); 
three(); 

//Output- one, two, three
```

- Asynchronous code will get executed after top lever synchronous function. 
- The event loop handles this with the concepts of a stack and a queue. 
- If you want to run **two()** function before three. You could use a callback function. 

---

#### Stack

The stack, or call stack, holds the state of what function is currently running. If you're unfamiliar with the concept of a stack, you can imagine it as an array with "Last in, first out" **(LIFO)** properties. 

```js
// Example Function

function one() {
    console.log(`one`); 
}

function two() {
        console.log(`two`);        
    }

function three() {
    console.log(`three`); 
}


// call these function
one(); 
two(); 
three(); 

//Output- one, two, three
```

The browser will handle execution for this synchronous code in the following manner. 

**PSEUDOCODE**

- Add `one()` to the stack, run `one()` which logs 'one' to the console, remove one() from the stack. 
- Add `two()` to the stack, run `two()` which logs 'two' to the console, remove two() from the stack. 
- Add `three()` to the stack, run `three()` which logs 'one' to the console, remove three() from the stack. 

#### Queue

The queue also referred to as a message queue or task queue, is a waiting area for functions. Whenever the call stack is empty, the event loop will check the queue for any waiting messages, starting from the oldest message. Once it finds one, it will add it to the stack, which will execute the function in the message. 

> Event loop uses the stack and queue to handle execution order of code

 ---

 **The browser will handle execution for this asynchronous code in the following manner** 

 ```js
 // Example Function
 
 function one() {
 console.log(`one`); 
 }
 
 function two() {
 setTimeout(() => {
   console.log(`two`);        
 }, 0)
 }
 
 function three() {
 console.log(`three`); 
 }
 
 
 // call these function
 one(); 
 two(); 
 three(); 
 
 //Output- 1, 2, 3
 ```

 

 Add **one()** to the stack, run the one() which logs 'one'  to the console,remove one()  from the stack. 

 - Add **two()** to the stack, run two(). Add `setTimeout()` to the stack, run the **setTimeout()** Web API which starts a timer and adds the anonymous function to the queue, remove **setTimeout()**  from the stack. Remove **two()** from the stack. 
 - Add `three()` to the stack, run three() which logs `three` to the console, remove three() from the stack. 
 - The event loop checks the queue for any pending messages and finds the anonymous function from the **setTimeout()**, adds the function to the stack which logs `two` to the console, then removes it from the stack. 

---

## Callback function

Callback function does not have a special syntax that is just a function that has been passed as an argument to another function. 

```js
// Example Function

function one() {
    console.log(`one`); 
}

function two() {
    setTimeout(() => {
        console.log(`two`);
        callback(); 
      }, 0)
    }

function three() {
    console.log(`three`); 
}


// call these function
one(); 
two(three); 

//Output- one, two, three
```

The function that takes another function as an argument is called a **high-order function**. According to this definition, any function can become a callback function if it is passed as an argument. Callbacks are not asynchronous by nature but can be used for asynchronous purposes. 

---

## Promises

A promise represents the completion of an asynchronous function. It is an object that might return a value in the future. It is an object that might return a value in the future. It accomplishes the same basic goal as a callback function, but with many additional features and more readable syntax. 

```js
// Initialize
const promise = new Promise((resolve, reject) => {})
```

![Event loop, callback and promises in JS.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1610348311485/kq3uQSVHp.png)

#### Consuming a Promise

Promises have a method called then that will run after a promise reaches resolve in the code. Then will return the promise's value as a parameter. In order to handle the error, you will use the catch instance method. This will give you a failure callback with the error as a parameter. 


![Event loop, callback and promises in JS 1.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1610348327693/Lnq0UnC8_.png)
---

⚡Thank Your For Reading | Happy Coding🥂

<a href="https://www.buymeacoffee.com/rahxuls" target="_blank"> <img src="https://res.cloudinary.com/rahulism1/image/upload/v1608182430/bmc_nbxakd.png"></a>