View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

What are Promises in Angular? Syntax, Examples, Future

By Pavan Vadapalli

Updated on Oct 24, 2024 | 9 min read | 20.5k views

Share:

JavaScript is single-threaded which means it is inherently synchronous. Thus, code runs line by line on the processor. But, suppose we have a functionality that needs to wait for something such as fetching a file, any web results, or other activity like this, in that case, making the wait to the application until the previous operation is finished is not efficient and it is considered as a major point of failure in any such application. To overcome this JavaScript, we can apply asynchronous behavior.  

After the execution, we would want to do different operations with the data gotten from these async functions as all our synchronous code runs before async ones. JavaScript provides three mechanisms for doing that: 

  • Callback Functions 
  • Promise Objects 
  • Async Functions 

We can use callback functions but there is a major drawback of using callbacks in a situation where we need to carry out a series of async operations with the next operation dependent on data from the previous one. 

To do this with callbacks we end up nesting callbacks inside callbacks, making our code very hard to read and error handling becomes a nightmare.  

  • The alternative to this is Promises. 
  • In Angular asynchronous behavior is handled using $http and $resources services. 

What are Promises in Angular?

A promise in angular is a JavaScript object which produces a value after an async operation is executed successfully. If the operation does not execute successfully, then it generates an error. 

A promise in angular is a class-based object, it is created using the new keyword and its constructor function. It contains different types of methods that give sour objects some power. 

A promise in Angular is defined by passing a callback function also known as the executor function or executor code as an argument to the Promise constructor. The executor function usually takes two arguments: resolve and reject. 

An async operation is defined inside the executor function and intended result or error if any occurred is handled by the resolve and reject handlers respectively. 

Sign up for a Master of Science in Computer Science from LJMU and master programming skills taught by industry experts.

Syntax of Promises in Angular

Here below is the syntax: 

const myPromise = new Promise((resolve, reject) => { 
    setTimeout(() => { 
          resolve('this is a promise'); 
    }, 300); 
}); 
myPromise.then((value) => { 
     console.log(value); 
      // expected output: "this is a promise" 
}); 
console.log(promise1); 
// expected output: [object Promise] 

Promise objects have a .then and a .catch methods which handle fulfilled results and errors if any occurred. They receive the outcome of async operations as data or error from the resolve and reject handler in the promise constructor. 

Learn more about what is promise in Angular by participating in a Full Stack Software Development Bootcamp.

3 States of Promises in Angular

Also, Promises in Angular has these states: 

  • Pending: This is an initial state, which is neither fulfilled nor rejected. 
  • Fulfilled: This means that the operation is completed successfully. 
  • Rejected: This means that the operation has failed. 

A promise in Angular is said to be settled if it is either fulfilled or rejected. It cannot be in pending state. 

.then  

.then method runs immediately after the promise has been fulfilled or after resolve is called. 

.then takes a callback function which receives the result when resolve is called. Ie. .then(function). The callback function inside .then takes result as an argument. Result is the value that we passed on to resolve as an argument when calling it. Ie. Resolve(value)  

.catch 

.catch runs immediately after reject(error) executed by the executor. That is after the promise has been rejected 

.finally 

The finally handler runs after the promise is settled. Settled means that the promise is either fulfilled or rejected. Whether the promise was fulfilled or rejected. Finally is always going to run. It does not process a promise but rather finalizes everything after the previous operations have been completed.  

Now, we know that .then and .catch methods returns promises hence they can be chained. 

source

Example of Promises in Angular

To demonstrate the use of Promises in angular let us see an example using Promises: 

let 

promise = new Promise((resolve, reject)=>{ 
      setTimeout(()=>{ 
            let count = 5 
      if(count == 5){ 
            resolve("done") 
      }else{ 
            reject(new Error("Ooops something went wrong)) 
      } 
    }, 2000) 
} ) 
Promise 
.then((result)=>{ 
      console.log(result) 
}) 
.catch((error)=>{ 
      console.log(error) 
}) 
.finally(()=>{ 
      console.log("Everything is finalized") 
}) 

Output: 

Done 

Everything is finalized 

Solution: The conditional if statement evaluates to true because count = = 5. resolve(done) is then called and the value “done” is passed onto .then as a result. Hence “done” is logged onto the console. .finally is then executed and logs “Everything is finalized” to the console. 

Chaining Promises in Angular

There is a prevailing need to execute two or more asynchronous operations next to next sequentially, where each next operation starts when the previous operation succeeds, with the result from the prior operation. We manage this by designing a promise chain. 

In other words, after producing code performs a task and gets the result, we usually want to do something different with that result. But we cannot directly access that result. We have to use .then method. The .then method returns a new promise, different from the original promise: 

const myPromise = doSomeAction(); 
const myPromise2 = promise.then(succeedCallback, failedCallback); 

This second promise(myPromise2) represents the completion of doSomeAction as well as the completion of succeedCallback and failedCallback we passed in, which can be other async functions returning a promise. When it happens, any callbacks added to myPromise2 get in line behind the promise returned by either succeedCallback or failedCallback. 

Basically, each promise in angular represents the completion of another async step in the chain of promises.  

For example: 

taskOne() 
  .then(function (result) { 
    return taskTwo(result); 
  }) 
  .then(function (newResult) { 
    return taskThree(newResult); 
  }) 
  .then(function (lastResult) { 
    console.log(`Receive the last result: ${lastResult}`); 
  }) 
  .catch(failureCallback); 

Chaining After a Catch: 

After catching an error, it is also possible to chain. That means .catch method is useful to achieve new actions even after an action failed in chain, we can accomplish remaining actions without any error. 

For example: 

new Promise((resolve, reject) => { 
  console.log("Start"); 
 
  resolve(); 
}) 
  .then(() => { 
    throw new Error("Something has failed"); 
 
    console.log("Do this action1"); 
  }) 
  .catch(() => { 
    console.error("Do this action2"); 
  }) 
  .then(() => { 
    console.log("Do this action compulsory without looking what happened at previous"); 
  });  

Output: 

Start 

Do this action2 

Do this action compulsory without looking what happened at previous 

How to Define Our Own Promises?

Here we are going to learn to define our Promise class myPromise: 

Following properties are defined in constructor: 

  1. state: These states can be either PENDING, FULFILLED or REJECTED 
  2. handlers: Handlers stores callback of .then, .catch and .finally methods 
  3. value: This is the resolve or rejected value  

A promise in angular is executed very rapidly. It executes as soon as it is created, that way our promise callback function will be called inside the constructor with the methods - reject and resolve. And these methods are passed as parameters to the function. 

Below is the example of Promise definition: 

const STATE = { 
    PENDING:’PENDING’, 
    FULFILLED:’FULFILLED’, 
    REJECTED:’REJECTED’, 
} 
class myPromise{ 
    constructor(callback){ 
        //Initial state of Promise is empty 
        this.state = STATE.PENDING; 
        this.value = undefined; 
        this.handlers = []; 
        //Invoke callback by passing the _resolve and _reject functions of our class 
        try{ 
            callback(this._resolve, this._reject); 
        }catch(err){ 
            this._reject(err) 
        } 
    } 
    _resolve = (value) => {} 
    _reject = (error) => {} 
    .then(onSuccess, onFailure){} 
    .catch(onFailure){} 
    .finally(callback){} 
} 

 

Future of Promises in Angular

Promises play a significant role in the Angular framework and because of concepts of ES6, importance of Promises is going to increase in JavaScript in the future. Thus, it can further be called a fundamental component of modern-day JavaScript.   

Promises in Angular are the ideal choice for managing async operations in a simple manner. They can support better error handling than callbacks and events in Angular. Thus, we can avoid undesired situations like callback hell.  

Promises in angular do provide a better chance for a user to read and understand the code in a more simple and efficient manner especially when that particular code is used for implementing multiple asynchronous operations. Because of all these reasons, Promises will be used on large scale in ale in Angular.  

 

Coverage of AWS, Microsoft Azure and GCP services

Certification8 Months

Job-Linked Program

Bootcamp36 Weeks

Conclusion

Angular promises are a placeholder holding the result of an async operation. If the operation completes successfully, then the promise fulfills with the operation value, but if the operation fails, the promise rejects and becomes the reason for the failure.  

Angular promises can also build chains, which are valuable in handling multiple inter dependent async operations.  

There is a lot more to the angular promises than then(), catch(), finally() methods which are the instance methods and chaining of promises. There are static methods as well as instance methods in the promises in Angular. upGrad Executive PG Programme in Full Stack Development from IIITB will comprehensively guide you in mastering programming and development. 

Boost your software engineering skills with our top programs. Explore the courses below to find the right fit

Master in-demand software skills with our specialized courses. Explore your options below to upskill today

Frequently Asked Questions (FAQs)

1. Why Promises used in Angular?

2. What is Promise used for?

3. What is Promise all in Angular?

Pavan Vadapalli

900 articles published

Get Free Consultation

+91

By submitting, I accept the T&C and
Privacy Policy

India’s #1 Tech University

Executive PG Certification in AI-Powered Full Stack Development

77%

seats filled

View Program

Top Resources

Recommended Programs

upGrad

AWS | upGrad KnowledgeHut

AWS Certified Solutions Architect - Associate Training (SAA-C03)

69 Cloud Lab Simulations

Certification

32-Hr Training by Dustin Brimberry

upGrad

Microsoft | upGrad KnowledgeHut

Microsoft Azure Data Engineering Certification

Access Digital Learning Library

Certification

45 Hrs Live Expert-Led Training

upGrad

upGrad KnowledgeHut

Professional Certificate Program in UI/UX Design & Design Thinking

#1 Course for UI/UX Designers

Bootcamp

3 Months