Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
KnowledgeHut upGradKnowledgeHut upGradBackend Development Bootcamp
  • Self-Paced
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

What are Promises in Angular? Syntax, Examples, Future

Updated on 24 October, 2024

19.93K+ views
9 min read

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.  

 

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?

Promises are used to handle asynchronous operations in Angular. They are easy to control when managing multiple async operations. Because if callbacks are used, they can create callback hell leading to unmanageable code. Because of these reasons promises are used in Angular. 

2. What is Promise used for?

A promise in angular is an efficient way to handle asynchronous operations. It is used to find out if the asynchronous operation is successfully completed or not. 

3. What is Promise all in Angular?

It combines multiple promises in Angular into a single promise. That single promise is resolved when all of the input promises are resolved. It returns a single promise that will be resolved with an array of values. Each value of the array corresponds to the promise at the same index/key in the promises array. If any of the promises are resolved with rejection, then this resulting promise will be rejected with the same rejection value. 

RELATED PROGRAMS