JavaScript and JQuery Essentials Trainin... (30 Blogs)
AWS Global Infrastructure

Front End Web Development

Topics Covered
  • AngularJS (36 Blogs)
  • The Complete WebDeveloper (43 Blogs)
  • ReactJS (7 Blogs)
  • JavaScript and JQuery Essentials Training (30 Blogs)
SEE MORE

How To Implement Promises in JavaScript?

Published on Aug 13,2019 1000 Views


Promises In JavaScript are basically used to handle operations asynchronous operations. A promise is an object which may produce a single value in the future: either a resolved value, or an error.

Following pointers will be covered in this article,

Let us get started with this article on Promises in JavaScript

Importance:

The promises come in handy when there are multiple asynchronous operations to be dealt with. Before promises were introduced in JavaScript, there were events and callback functions being used to handle asynchronous operations. Since events are not much useful in case of asynchronous operations, they are not preferred. Coming to callback, using them in multiples would create such a mess that it was very difficult for anyone to understand the code.
Therefore Promises are the first choice of every coder to handle asynchronous operations in the simplest manner. They have advanced features which makes it easy for them to handle the operations than callback and events.

  • Promises makes the code readable which means it can be edited by the coders at later stage of development also.
  • There is better handling throughout the asynchronous operations as compared to callback and event.
  • Advanced error handling is also considered as an important feature.
  • A much better flow of control definition in asynchronous is there.

Moving on with this article on Promises in JavaScript

Type of states:

Fulfilled: Related to those promises which are succeeded.
Rejected: Related to those promises which are rejected.
Pending: Related to those promises which are pending i.e. neither rejected nor accepted.
Settled: Related to those promises which are being fulfilled or rejected.

Moving on with this article on Promises in JavaScript

Creation of Promises

A promise is created using promise constructor.

Syntax:

var promise = new Promise(function(resolve, reject){
//do something here 
});

Parameters:
Promise constructor takes one argument, callback function. There are two arguments in callback function, resolve or reject. Operations are performed inside the callback functions, if everything went well then call resolves otherwise call gets rejects.

Moving on with this article on Promises in JavaScript

Example 1:

var promise = new Promise(function(resolve, reject) { 
/*declaring and defining two variables of const data type with same content.*/
const a = "Hello there! My name is Yash and I am interested in computer Science."; 
const b = " Hello there! My name is Yash and I am interested in computer Science.";
//checking if both the content stored in variables are same or not
if(a === b) { 
//calling resolve 
resolve(); 
} else { 
//calling reject
reject(); } 
}); 
promise. 
then(function () { 
console.log('Promise Resolved!!'); 
}). 
catch(function () { 
console.log('Promise Rejected!!'); 
});

Output:
Output- Promises in JavaScript- Edureka

Moving on with this article on Promises in JavaScript

Example 2:

var promise = new Promise(function(resolve, reject) {
//initializing two variables with integer values
const x = 11+2;
const y = 26/2;
//checking if both variables are equal or not
if(x === y) {
//calling resolve
resolve();
} else {
//calling reject
reject(); }
});
promise.
then(function () {
console.log('Promise is Resolved!!');
}).
catch(function () {
console.log('Promise is Rejected!!');
});

Output:
Output- Promises in JavaScript- Edureka

Moving on with this article on Promises in JavaScript

Example 3:

var promise = new Promise(function(resolve, reject) { 
const i = "Hello";
const a = "World"; 
//performing addition of two variables to store value in another variable
const j= i+a;
if((i+a) === j) { 
//calling resolve
resolve(); 
} else { 
//calling reject
reject(); } 
}); 
promise. 
then(function () { 
console.log('Promise is Resolved!!'); 
}). 
catch(function () { 
console.log('Promise is Rejected!!'); 
});

Output:
Output- Promises in JavaScript- Edureka

Moving on with this article on Promises in JavaScript

Consumers in Promises

There are two registering functions:

then()

When a promise is either resolved or rejected, then() is invoked.

Parameters:

  • If promise is resolved, first function is executed and a result is received.
  • If promise is rejected, second function is executed and an error is displayed on the screen.

Syntax:

.then(function(result){
//handling  success
}, function(error){
//handling the error
})

Moving on with this article on Promises in JavaScript

Example

When promise is resolved

//resolving of promise
var promise = new Promise(function(resolve, reject) { 
resolve('Success message is written here!'); 
}) 
promise 
.then(function(successMessageishere) { 
//success handling function is invoked 
console.log(successMessageishere); 
}, function(errorMessageishere) { 
console.log(errorMessageishere); 
})

Output:
Output- Promises in JavaScript- Edureka

Moving on with this article on Promises in JavaScript

When promise is rejected

//Rejection of promise
var promise = new Promise(function(resolve, reject) { 
reject('Rejection message is written here!') 
}) 
promise 
.then(function(successMessage) { 
console.log(successMessage); 
}, function(errorMessage) { 
//error handler function is invoked 
console.log(errorMessage); 
})

Output:
Output- Promises in JavaScript- Edureka

Moving on with this article on Promises in JavaScript

Catch()

Whenever there is some sort of error or the promise gets rejected during execution time, catch() is invoked.
Parameters:

  • Only one function is passed as parameter in catch() method.
  • This function is built to handle errors or promise rejections.

Syntax:

.catch(function(error){
//handling error
})

Moving on with this article on Promises in JavaScript

Example 1:

var promise = new Promise(function(resolve, reject) { 
reject('Promise is Rejected') 
}) 
promise 
.then(function(success) { 
console.log(success); 
}) 
.catch(function(error) { 
//error handler function is invoked 
console.log(error); 
});

Output:
Output- Promises in JavaScript- Edureka

Moving on with this article on Promises in JavaScript

Example 2:

var promise = new Promise(function(resolve, reject) { 
//error message
throw new Error('There is some error!') 
}) 
promise 
.then(function(success) { 
console.log(success); 
}) 
.catch(function(error) { 
//error handler function is invoked 
console.log(error); 
});

Output:
Output- Promises in JavaScript- Edureka

Moving on with this article on Promises in JavaScript

Example 3:

var promise = new Promise(function(resolve, reject) { 
//error message can be edited here
throw new Error('some error occured !') 
}) 
promise 
.then(function(Thissuccess) { 
console.log(Thissuccess); 
}) 
.catch(function(Thiserror) { 
//error handler function  invoked 
console.log(Thiserror); 
});

Output:
Output- Promises in JavaScript- Edureka

Application:
1. Handling asynchronous events.
2. Handling asynchronous http requests.

Thus we have come to an end of this article on ‘Promises in JavaScript’. If you wish to learn more, check out the Java Training by Edureka, a trusted online learning company. Edureka’s Java J2EE and SOA training and certification course is designed to train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

Got a question for us? Please mention it in the comments section of this blog and we will get back to you as soon as possible.

Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

How To Implement Promises in JavaScript?

edureka.co