
Like in our physical life, we have promises in the same way in JS we have promises but the question arises why do we need promises in JS?
Well even though Java Script seems all mighty and powerful but even might Thor needs Avengers to save the world. In the same way, JS also depends on the third-party sometimes like getting the data, and functionality. Now, these third parties will work independently taking their sweet time getting the data, and till then what JS suppose to do? Wait… Nope, it will move forward with other tasks which are at hand.
So before we move forward with Promises we need to understand how exactly execution will happen in Java Script
So whatever you write in your javascript file the compiler will read it and creates an environment also known as the execution context
Let’s take a simple example here.
var numVar =2;
function doubleNum(num){
return num*2;
}
We have a variable called numVar and function called doubleNum.
Now JavaScript will read the code line by line so
First, it will read that it has a variable called numVar so it will create a memory.
Then it will create a memory for function doubleNum and add the function.
So this reading code line by line from top to bottom is called single-threaded nature.
Now we have an execution context. The execution context can be of two types — Global, Function

There are two phases of execution context:
Creation
Execution
The above diagram is the creation phase of execution context.
and when the execution in our example num holding value 2 and function doubleNum execute
is called Execution phase.
In execution phase all the execution is stack together also called execution stack
Now when we deal with simple tasks which run line by line also known as synchronous task.
There are other types as well you remember we talked about them in our intro yes the third party independent one also sometime know as asynchronous task.
Asynchronous task can be defined as that is initiated now but will be executed later and some examples can your api calls , setTimeOut, setIntervals.
Now question arises how JS deals with asynchronous tasks I mean the application should be running and when these tasks are running parallelly.
So we have something execution queue in our execution context and whenever they deal with asynchronous task they will be removed from execution stack and placed inside execution queue and once the execution stack is empty executions placed inside execution queue is moved to execution stack with something called event loops.

This is the behind the scene what happens in JavaScript.
Now these execution queues methods and can be accessed using a call back function.
What is a callback function — a function which is a parameter to another function is called callback function and function which accepts another function as an argument is called higher order function.
function(callback1){
callback1(callback2);
}
callback1(callback2){
callback2(callback3);
}
the above example is one scenario where you there is nesting of callbacks inside call back functions and is also known as callback hell.
To avoid this problem we have a saviour which was introduce in ES6 and that was promise. Promise is an asynchronous object which is returned with eventual completion. Now like in real life there could be three ways any promise will result — pending, resolve, rejected.
Every promise before fulfilling is in pending state or promise is made but the result will be in future state.
If the promise is fulfilled it will be in resolve state but if some error occurs then it is in reject state or commonly known that the promise is rejected.
So you can create any promise with new keyword and add Promise
const promise = new Promise(function(resolve,reject){
//.... do something
})
Inside the promise class will have a function called executor and it will be executed whenever we try to access promise.
The executor has two parameters resolve , reject. If you send resolve you promise was successful but if you send reject it will throw error.
const promise = new Promise(function(resolve, reject){
resolve('Promise was successful');
})
const promise = new Promise(function(resolve, reject){
reject('Promise can not be completed');
})
In this way you can create your own promise in javascript and can send the promise object in the form of resolve or reject.
Note: A promise can resolve or reject only once and whatever is called first will work.
const promise = new Promise(function(resolve, reject){
reject('No this promise can not be fulfilled');
resolve('I think I can do something')
})
In the above case reject will work and resolve will be not considered as when JS will see reject it will take reject would immediately move out of promise and will not run the line after that.
we know how to create a promise well we should also know how to open a promise.
Since promise has executor it called opened by just calling. So how to open a promise.
promise can be opened using methods — .then, .catch,.finally
Whenever we get a promise object we should be prepared for both the scenarios — resolve or reject and to do that we can use then and catch.
const promise = new Promise(function(resolve, reject){
resolve('Promise was successful');
})
// That's how you can open a promise
promise.then((res)=>{
console.log(res) // Promise was successful
}).catch((err)=>{
console.log(err) // In case of reject whatever is send with reject will be here
}).finally(()=>{
console.log('Promise is fulfilled');
})
So in case of resolve the data can be taken in then , in case of reject data can be taken in catch and if we want do something irrespective of result whether it is resolve or reject we can run it n finally.
Do you remember the callback hell we talk about earlier well let’s see how we can handle that situation using promise.
promise.then((res)=>{}).then((res)=>{}).then((res)=>{})
This chain of then is called promise chaining as it is opening one promise one after the other.
You can catch error using catch even the executors have invisible try and catch with them and in case of any error it will be caught by nearest catch and will be shown.
new Promise((resolve,reject)=>{
someUnknownFunction(); //non existence function
}).catch((err)=>{console.log(err)}) // it will be catched here
Another very good example can be this.
new Promise(function(resolve,reject){
throw new Error('Whoops')
}).catch((err)=>{
console.log(err) // Whoops
}).then(()=>{
console.log('I will run')// This will be printed
})
So in the above example when first error will be thrown it will be caught by catch and code will run as usual and then will be run.
Don’t worry JS got you covered we have Promise API for that.
So we have to run multiple promises in parallel and want the result after all the promises were fulfilled we can go with.
const prom = Promise.all([new Promise(resolve => resolve('First Promise')),new Promise(resolve => resolve('Second Promise')),new Promise(resolve => resolve('Third Promise'))]);
prom.then((res)=>{
console.log(res) // ["First Promise","Second Promise","Third Promise"]
})
The only issue is if one of the promise fails rest of resolve result will be ignored.
const prom = Promise.all([new Promise(resolve => resolve('First Promise')),new Promise((resolve,reject) => reject('Second Promise')),new Promise(resolve => resolve('Third Promise'))]);
prom.then((res)=>{
console.log(res)
}).catch(err =>{
console.log(`${err} is the error`)
})//Second Promise is the error
To avoid that we have a recent edition
It will going to return the status of each promise whether they are resolves or rejected.
const prom = Promise.allSettled([new Promise(resolve => resolve('First Promise')),new Promise((resolve,reject) => reject('Second Promise')),new Promise(resolve => resolve('Third Promise'))]);
prom.then((res)=>{
console.log(res) // [{status: "fulfilled", value: "First ...},{status: "rejected", reason: "Second Promise' ...},{status: "fulfilled", value: "Third ...}]
}).catch(err =>{console.log(`${err} is the error`)})
This is all for now so for small recap we learned about — execution context, execution stack, queue, event loop, callback functions, asynchronous tasks, Promises.
I hope this article helped you in your journey of becoming a web developer.
