# JavaScript Promise Methods Explained Through Air Traffic Control

In a airport wether it is busy or not it always consists of Air Traffic Control(ATC) Room which is located on top of a high rise tower like building. Its work is to give directions to flights crossing , taking off , landing or taxing. It takes requests from flights and accordingly fulfill or deny it. Some decisions are instant , but some require multiple safety checks.

Similary there is async javascript which consists of Promise , whose working is in same pattern as ATC. It is as follows:  

*   Flight request ---> Promise
    
*   ATC ------> Decision System
    
*   Clearence -----> resolve
    
*   Denial -------> reject
    

So we are going to understand methods of promise with the analogy of ATC , which will help to understand each method very easily.

But before we will have a look at Promise Lifecycle. Consider a single plane scenerio.

## Basic Promise Lifecycle

### Pending

A pilot requests landing clearnece to ATC, ATC respons by stand by. So this is a pending state A request has been made but currently no outcome is there.

Now there can be two outcomes or possibilites.

### Fulfilled

If ATC responds with Cleared to Land then the crequest is fulfilled.

### Rejected

If ATC responds if runway is packed , closed or to divert the flight , so this condition is rejected , the Promise is not fulfilled and is rejected.

## Understanding the Methods:

### .then() - *What happens if cleared to land*

ATC says : "Cleared to land" . The pilot begin landing procedure.

```javascript
const landingRequest = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("Cleared to land");
  }, 2000);
});

landingRequest.then((message) => {
  console.log("Pilot:", message);
  console.log("Landing the aircraft...");
});
```

.then() runs only when a promise is resolved , it recieves the resolved value. So to get the value of a promise when it's fulfilled , we call then() method of the promise object.

### .catch() - *What if landing is denied*

If ATC rejects the request (Promise) of flight to land , then pilot handles it by divertng to other airport , or whatever SOP may be.

```javascript
const landingRequest = new Promise((resolve, reject) => {
  setTimeout(() => {
    reject("Runway closed");
  }, 2000);
});

landingRequest.catch((error) => {
  console.log("Pilot:", error);
  console.log("Diverting aircraft...");
});
```

catch() method runs only when promise is rejected. It handles error safely. Here in the scene catch() method is depicted by diverting the flight or following the SOP.

### .finally() - *It will happen no matter what the case is*

Wether cleared or denied to land , a report must be sent to airline headquarters.

```javascript
landingRequest
  .then(() => console.log("Landing successful"))
  .catch(() => console.log("Landing denied"))
  .finally(() => console.log("Reporting to airline HQ"));
```

finally() runs in both success and failures . Used for cleanup/logging. Sending the report to HQ of airline is the task need to be done irrespective of outcome.

### Promise.resolve() - *Instant clearence*

The runway is empty and atc immediatly cleared the request and now flight has resolved promise or request and can act.

```javascript
const clearance = Promise.resolve("Cleared instantly");

clearance.then(console.log);
```

Promise.resolve() is used when we already have a success value and want a Promise.

### Promise.reject() - *Instant Denial*

There's a emergency on runway and ATC instantly denies landing .

```javascript
const denial = Promise.reject("Runway emergency");

denial.catch(console.log);
```

Promise.reject() creates and returns apromise that is already rejected.

### Promise.all() - *All safety checks must pass to have a safe landing*

Before landing and giving clearence to flight atc checks for Weather, Runway inspection, fuel confirmation. All must pass the criteria set then only the landing promise can be fulfilled. Even if one of the checks failed in test , landing will be denied.

```javascript
const weatherCheck = Promise.resolve("Weather clear");
const runwayCheck = Promise.resolve("Runway safe");
const fuelCheck = Promise.resolve("Fuel sufficient");

Promise.all([weatherCheck, runwayCheck, fuelCheck])
  .then((results) => {
    console.log("All checks passed:", results);
    console.log("Landing approved");
  })
  .catch((error) => {
    console.log("Landing denied:", error);
  });
```

If even one fails entire Promise fails.

### Promise.allSetteled() - Full report needed

ATC wants report from all departments to work properly for the flights. Even if any of them fails , they want complete data with 'reason' if failed.

![](https://cdn.hashnode.com/uploads/covers/67e6a7fb7998e98bb566bd03/e271d379-8e91-4740-850d-b4d871380791.png align="center")

```javascript
const weatherCheck = Promise.resolve("Weather clear");
const runwayCheck = Promise.reject("Runway damage");

Promise.allSettled([weatherCheck, runwayCheck])
  .then((results) => {
    console.log("Full Report:", results);
  });
```

Output:

```javascript
Full Report: [
  { status: "fulfilled", value: "Weather clear" },
  { status: "rejected", reason: "Runway damage" }
]
```

Each result include status wether 'fulfilled' or 'rejected; and value or reason respectivly.

### Promise.race() - *Any One Approval Is Enough*

Flight is in emergency situation amidst its journey , it contacts 2 airports ans whichever responds first , pilot follows that.

```javascript
const airportA = new Promise((resolve) =>
  setTimeout(() => resolve("Airport A cleared"), 3000)
);

const airportB = new Promise((resolve) =>
  setTimeout(() => resolve("Airport B cleared"), 1000)
);

Promise.race([airportA, airportB])
  .then(console.log);
```

First settled promise wins , here we can see from creatd situation it is airportB.

### Promise.any() - Any one approval is enough

If from the above situation , pilot sends request or asks for Promise from 5 airports which are very busy at the point . If any one approves safe landing is possible .

```javascript
const A = Promise.reject("A denied");
const B = Promise.reject("B denied");
const C = Promise.resolve("C cleared");

Promise.any([A, B, C])
  .then(console.log)
  .catch((error) => console.log("All denied:", error));
```

Promise.any() resolves on first success . It gets rejected only if all fails.

### Promise.withResolvers() - *Manual ATC control and external approvals*

Consider a situation of a mid flight , in which a security -alert appears of overheat and chances of catching fire are increasing within flight. The aircraft must divert and must land to nearest airport , but nearest is military airbase.  
ATC cannot decide alone to give the clearence to land , as it may cause a naational threat.

Approval must come from Defence , NSA. Pilot has requested and is waiting , ATC is also in wait for the decsions from respective ministries and departments.

```javascript
const { promise, resolve, reject } = Promise.withResolvers();
```

*   promise → The pending diversion approval
    
*   resolve → Ministry says “Approved”
    
*   reject → Ministry says “Denied”
    

![](https://cdn.hashnode.com/uploads/covers/67e6a7fb7998e98bb566bd03/b27e9d2a-9635-4553-aafa-6d71f1b9e9b0.png align="center")

What ATC can do is simply:

```javascript
promise
  .then(msg => announce(msg))
  .catch(err => emergencyProtocol(err));
```

So the concept of the withResolvers() method is to help to call functions like reolve , reject from outside the Promise constructor.  
The older way to call functions outside of constructor was this:

```javascript
let resolveFn, rejectFn;

const promise = new Promise((resolve, reject) => {
  resolveFn = resolve;
  rejectFn = reject;
});

// Now we can call anywhere:
resolveFn("Done");
```

But now with Promise.withResolvers() we can write it in a cleaner way.

```javascript
const { promise, resolve, reject } = Promise.withResolvers();

// Anywhere in the code
resolve("Completed!");
```

So from the analogy , ATC prepared the flight requestfile , Approval and reject button , later when decison is called from external means from other departments , then press one button.  
*(It is somewhat hypothetical just to understand the method).*

It gives you 3 things:

| Item | Meaning |
| --- | --- |
| promise | The actual Promise |
| resolve | Function to approve |
| reject | Function to deny |

You control when to call resolve/reject.

## Final Summary Table:

Comparing Promise methods to ATC world.

| **JavaScript** | **ATC Meaning** |
| --- | --- |
| resolve | Landing cleared |
| reject | Landing denied |
| .then() | Begin landing |
| .catch() | Divert plane |
| .finally() | Report decision |
| all() | All checks must pass |
| race() | First airport response |
| any() | Any one airport approval |
| allSettled() | Full report |
| resolve() | Instant clearance |
| reject() | Instant denial |
| withResolvers() | Manual decision control |
