For enquiries call:

Phone

+1-469-442-0620

HomeBlogWeb DevelopmentWhat are Promises in Angular: Beginners' Guide

What are Promises in Angular: Beginners' Guide

Published
25th Apr, 2024
Views
view count loader
Read it in
9 Mins
In this article
    What are Promises in Angular: Beginners' Guide

    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. 

    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. 

    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. 

    what is promise in angular

    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. 

    For more such Angular promise examples and easy understanding of concepts you can go through the Angular training 

    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 

    Defining 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){} 
    } 

    Check out the web development online course for more understanding of the topic-related Angular Promises examples. You can explore more concepts related to Angular promises. 

    Future of Promises

    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.  

    Are you ready to unlock the power of Python? Join our Python course online and discover the endless possibilities of this versatile language. From web development to data analysis, Python has got you covered. Enroll now and embark on a coding journey like no other!

    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. We can also study more about the concepts like thenables, object tracking, etc. KnowledgeHut Angular training will help you understand the Promises in Angular in simpler and effective way. 

    Frequently Asked Questions (FAQs)

    1Why 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. 

    2What 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. 

    3What 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. 

    Profile

    Sachin Bhatnagar

    Blog Author

    Sachin Bhatnagar is an experienced education professional with 20+ years of expertise in Media & Entertainment and Web Technologies. Currently, as the Program Director - Full-Stack at KnowledgeHut, he excels in curriculum development, hands-on training, and strategic deployment of industry-centric educational programs. His online training programs on have attracted over 25,000 learners since 2014. He actively contributes to the development of full-stack training products, leveraging KnowledgeHut's advanced learning platform. Collaborating with organizational leaders, he ensures the success of these programs and has created several technology programs prominently featured in KnowledgeHut's course offerings.

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Select
    Your Message (Optional)

    Upcoming Web Development Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon