Angular 12 JavaScript Promise Example

In this Angular tutorial, we will understand Promises and how Promises work. We will discuss how to use ES6 Javascript Promises properly in Angular applications with examples.

Promises are TypeScript objects which are used to handle asynchronous operations in a program. A promise proves very helpful in managing single or multiple asynchronous operations like HTTPS calls and performs optimal error handling.

As we know JavaScript is a single-threaded programming language, due to which it waits for a previous statement to execute before moving to the next task. To tackle this synchronous behavior, we have Callback functions that take a specific task and sit aside to perform program execution asynchronously.

Callback functions wait for an event to get called.  In complex applications with loads of interactions and data input-output operations, the situation worsens, resulting in callback hell due to the nested callback functions.

ES6 TypeScript Promises

For modern applications, now we have ES6 Promises a solution to callback hell. These are more simple, better, and easy to maintain. In Angular 2+ applications, we usually use RxJS Observables which are far compatible with Angular Framework but Promises also getting more preference due to its latest upgraded JavaScript version supported by ES6.

Promises in JavaScript

Promises in JavaScript allow us to handle asynchronous operations. For example, we need to make an HTTP call to a remote server to fetch some data. As the completion of this HTTP, call depends on many factors and may take some time to complete, instead of waiting for its completion we can create a Promise and let the remaining program keep on running.

Promises are similar to callbacks and will let you know when data is fetched. But they support more features and methods to efficiently handle complex scenarios.

How to Create Promises?

An Es6 Promise takes an inner function, which accepts two parameters resolve and reject. When we execute a Promise, it gives us a surety that it is going to return us some value either it is a Success(resolve) or Failure(reject). That’s why we call them a Promise.

Have a look at the simple ES6 TypeScript Promise example.

var promise = new Promise(function(resolve, reject){
     // logic to return resolve or reject to complete a promise.
});

Above we defined a Promise with new operator and passing the resolve and reject parameters in the inner returned function. In the function body, we put the asynchronous code like HTTP call or setTimeout function.

 

States of a Promise

  • pending : This is the first/ initial state when the promise is yet to be fulfilled or rejected.
  • fulfilled : A state, when the promise is successfully executed and completed.
  • rejected : The state, when promise operation is failed and reject() function is returned.

 

TypeScript Promise Parameters

  • A new Promise object accepts a callback function.
  • This callback function takes 2 parameters i,e resolve and reject.
  • The either of resolve or reject are based on the asynchronous code we have in the function body.
var isTaskDone = true;
var promise = new Promise(function(resolve, reject) {
  setTimeout(function() {
	  if(isTaskDone) {
		resolve('Task Completed after 1 second!');
	  }else{
		reject('Task Not Completed after 1 second');
	  };
  }, 1000);
});
promise.then(function(value) {
  console.log(value); // OUTPUT Task Completed after 1 second!
});

Here in the example above, the isTaskDone is true, so after 1-second setTimeout the resolve() function will execute and return the string in it.

If something go wrong isTaskDone set to false or HTTP call fails due to network or server failure the reject() function will be called with the string returned.

We can return anything in resolve or reject methods like empty, string objects etc.

 

Angular TypeScript Promise Example

We can add success and error handlers with Promise. The Promise object can be used to handle Success and Error responses in the following ways.

Adding Success and Error Handlers in Promise using then()

We can catch the Succes(resolved) or Failed(rejected)  values inside the then() handler as shown below:

var isTaskDone = false;
var promise = new Promise((resolve, reject) => {
  setTimeout(() => {
	  if(isTaskDone) {
		resolve('Task Completed after 1 second!');
	  }else{
		reject('Task Not Completed after 1 second');
	  };
  }, 1000);
});
promise.then((value) => {
  console.log(value); // OUTPUT Task Completed after 1 second!
},(error) =>{
  console.error(error); // OUTPUT Task Not Completed after 1 second
});

Here have converted the functions into arrow/ lambda notations.  After setting the isTaskDone to false the error callback in then() is executed.

Using catch() to Handle Errors

Instead of using then() method to handle both Success and Errors callback, we can also use catch() method to handle errors as shown below:

var isTaskDone = false;
var promise = new Promise((resolve, reject) => {
  setTimeout(() => {
	  if(isTaskDone) {
		resolve('Task Completed after 1 second!');
	  }else{
		reject('Task Not Completed after 1 second');
	  };
  }, 1000);
});
promise.then((value) => {
  console.log(value); // OUTPUT Task Completed after 1 second!
});
promise.catch((error) => {
  console.error(error); // OUTPUT Task Completed after 1 second!
});

 

Conclusion

We discuss how easily w can use Promises in Angular applications using ES6 TypoScript. Promises make Sucess and Error handling a lot easier.

Leave a Comment

Your email address will not be published. Required fields are marked *