DEV Community

Cover image for Promises in Javascript
praveenreddy1798
praveenreddy1798

Posted on

Promises in Javascript

What is a Promise ?

A promise in JavaScript is just like a promise we make in our real lives.

Whenever we make a promise to someone or to ourselves we usually refer to an event that is going to occur in the future. Any promise that is made has three possible states:

  • Pending till the time of event
  • Fulfilled at the right time
  • Rejected

Promises in Javascript are used to handle asynchronous events and asynchronous http requests.
When we define a promise in JavaScript, it acts in a similar manner to a promise made in real life and can be:

  • pending - result is undefined
  • fulfilled - result is a value
  • rejected - result is an error object

For example, when we request a particular data from the server with the help of a promise, it will be in pending mode until we receive the data.

If we happen to get the right information from the server, the Promise will be resolved. But if we fail to get the required information, then the Promise will be in rejected mode.


Creating a Promise in Javascript

  1. Create a promise object using a constructor
var promise = new Promise();
Enter fullscreen mode Exit fullscreen mode
  1. Passing a function with two parameters to depict success(resolve) and for failure(reject)
var promise = new Promise(function(resolve, reject){
//condition
});
Enter fullscreen mode Exit fullscreen mode
  1. Defining a condition. If a condition is met the the promise is resolved otherwise it is rejected.
var promise = new Promise(function(resolve, reject){

if(condition) //condition is true
{
resolve();
}
else //condition is false
{ 
reject();
}
});
Enter fullscreen mode Exit fullscreen mode

Using a Promise in Javascript

Promise.then()

It takes two arguments, a callback for success and another for failure.

.then() can be used to handle both resolve and reject

Firstly, let's look at how .then() can handle resolve with an example

 var promise = new Promise(function(resolve, reject){
let x = 1;
if(x>0){
resolve('promise accepted')
}
else {
reject('promise rejected')
}
}
) 

promise.then(function(message){
console.log(message) // "promise accepted"
})

promise.catch(function(message){
console.log(message) 
})
Enter fullscreen mode Exit fullscreen mode

In the above example we can see how the promise is resolved when the condition x>0 is met and resolved message "promise accepted" is available in .then()

Now let's look at how .then() can handle reject with an example

var promise = new Promise(function(resolve,reject){
let x = 1;
if(x>0){
reject('promise rejected')
}
else {
resolve('promise accepted')
}
}
)
promise.then(function(message){
console.log(message)  // "promise rejected"
})
promise.catch(function(message){
console.log(message)
})
Enter fullscreen mode Exit fullscreen mode

In the above example we can see how the promise is rejected when the condition x>0 is met and rejected message "promise rejected" is available in .then()


Promise.catch()

.catch() can be used to handle errors and reject

Firstly, let's look at how .then() can handle reject with an example

 var promise = new Promise(function(resolve,reject){
let x = 0;
if(x>1){
resolve('promise accepted')
}
else {
reject('promise rejected')
}
}
)

promise.then(function(message){
console.log(message) 
})
promise.catch(function(message){
console.log(message) // "promise rejected"
}) 
Enter fullscreen mode Exit fullscreen mode

In the above example we can see how the promise is rejected when the condition x>0 is not met and rejected message "promise rejected" is available in .catch()

Now let's look at how .catch() can handle errors with an example

var promise = new Promise(function(resolve,reject){

if(x>1){
resolve('promise accepted')
}
else {
reject('promise rejected')
}
}
)

promise.then(function(message){
console.log(message) 
})
promise.catch(function(message){
console.log(message) // [object Error] { ... }
}) 
Enter fullscreen mode Exit fullscreen mode

In the above example we can see that there is a error because x is not defined and therefore it fails to check if the condition is true or false resulting in throwing a error message which is caught in the .catch() block.

Promises.all()

Promise.all() is a method that is very useful when we have multiple promises and we have to individually wait for each promise to complete before the next promise can be executed.

Promise.all() takes in a array of promises as input and resolves a single promise upon resolving all the promise objects in the array.
Even if one of promise object get rejected, the entire promise gets rejected.

Let's look into an example to understand more about it.

let cleanRoom = function(){
return new Promise(function(resolve,reject){
resolve('room cleaned')
})
}

let removeGarbage = function(){
return new Promise(function(resolve,reject){
resolve('garbage removed')
})
}

Promise.all([cleanRoom(),removeGarbage()])
.then(function(){
console.log('work finished') // "work finished"
})
.catch(function(){
console.log('work not finished')
})
Enter fullscreen mode Exit fullscreen mode

In the above example we can see that the promise is resolved with a output as "work finished" because the individual promise methods cleanRoom() and removeGarbage() are resolved

Now let's see what happens when one of the promise methods in the array are rejected

let cleanRoom = function(){
return new Promise(function(resolve,reject){
resolve('room cleaned')
})
}

let removeGarbage = function(){
return new Promise(function(resolve,reject){
reject('garbage not removed')
})
}

Promise.all([cleanRoom(),removeGarbage()])
.then(function(){
console.log('work finished') 
})
.catch(function(){
console.log('work not finished')//" work not finished"
})

Enter fullscreen mode Exit fullscreen mode

In the above example we can see that only removeGarbage() promise method was rejected and it resulted in the entire promise to reject with a output "work not finished" which is caught in the catch method.


Promise.race()

It is used when we need to return the result of the first resolved promise or rejected promise as soon as it is available.

The Promise.race() method returns a promise that fulfills or rejects as soon as any one of the promises in the input array of promises resolves or rejects.

Let's look into an example to understand about it.

let cleanRoom = function(){
return new Promise(function(resolve,reject){
resolve('room cleaned')
})
}

let removeGarbage = function(){
return new Promise(function(resolve,reject){
reject('garbage removed')
})
}

Promise.race([cleanRoom(),removeGarbage()])
.then(function(){
console.log('one of them finished') // "one of them finished"
})

.catch(function(){
console.log('one of them not finished')
})
Enter fullscreen mode Exit fullscreen mode

In the above example we can see that it checks only for the first promise method cleanRoom() and because it is resolved, the entire promise resolves giving an output "one of them finished" without even checking the removeGarbage() method thereby completing tasks faster.


If you liked this article, give it a ❤ 🦄 and Save it for later.

Top comments (0)