Angular – Promise Explained with Code Example

0

Promise, in Javascript, is a concept which allows the callee function to send back a promise (sort of assurance) to the caller function that it would, for sure, send back a resolution, be it a success or a failure at a little later point of time. The caller believes the callee if a promise is sent back, and, proceeds ahead with the program execution.

On a lighter note, the following comic strip represents the relationship between the caller and callee. As like the below, caller function can believe on callee function sending back Javascript promise object, which does result in the state of either resolution or a rejection (in case of errors).

Angular promise then resolve reject

Figure 1. Rest assured, promises are kept through resolution or rejection

In this post, you will learn about some of the following concepts in relation to promise concept vis-a-vis an angular app built with Angular 2.*, Angular 4.* and Angular 5.* versions:

  • Introduction to Promise
    • How to create a promise?
    • How to process a returned promise object?
    • What is promise chaining?
  • Promise with Angular Http Service
  • Promise with Angular HttpClient Service
  • Sample interview questions
  • Practice Test

Introduction to Promise with Code Examples

Here is a detailed introduction of promise concept with the help of code examples wherever appropriate:

  • Allows asynchronous operations to happen; Caller can proceed ahead with program execution if callee function returned a promise object.
  • How to create Promise using new operator: The following represents the sample code of a function which creates a Promise object using new operator and return the same:
    function printHelloWithPromise(name) {
        let promise = new Promise(function(resolve, reject) {
            // In place of the code given below, one can call REST APIs
            // For errors, one can choose to reject the promise;
            // For successful processing, promise can be resolved
            //
            const responseVar = 1+1;
            if(responseVar == 2) {
              resolve("Success: " + name);
            } else {
              reject("Error: " + name);
            }
        });
        return promise;
      }
    

    Note some of the following:

    • The result of code execution within promise could be processed appropriately to either resolve or reject the promise.
    • resolve method is used to resolve the promise in form of successful resolution
    • reject method is used to reject the promise if an error occurred
  • How to process a Promise object returned from callee function: The following represents the sample code for caller function processing the Promise object returned by the callee function:
    let greetingPromise = printHelloWithPromise("https://vitalflux.com");
    greetingPromise.then(function(resolveOutput) {
        console.log(resolveOutput);
    }, function(rejectOutput) {
        console.log(rejectOutput);
    });
    

    Note some of the following:

    • For resolution, function with resolveOutput is invoked
    • For error where the promise is rejected, function with rejectOutput value is processed.
  • What is Promise chaining?: The promise object can further be passed to another promise object which can then be passed to another promise object which could then choose to resolve or reject the promise. This process is called as chaining.

Promise & Angular Http Service

In this section, you will learn the usage of Promise with Angular Http service. The code given below works for Angular 2 and Angular 4 apps.

The following represents the code of a custom Angular Service. The code has an API namely getRx. The getRx API internally invokes a REST API call to get the prescription information from the server for a logged in user.

import {Http, Headers} from '@angular/http';
import {Injectable} from '@angular/core';
import {Rx} from './rx';
import {Cookie} from 'ng2-cookies';

@Injectable()
export class RxService {
    private rxUrl = 'http://localhost:8080/rx';

    constructor(private http: Http) {
    }

    getRx(): Promise<Rx[]> {
        let headers = new Headers({
            'Content-type': 'application/json',
            'Authorization': 'Bearer ' + Cookie.get('access_token')
        });

        return this.http.get(this.rxUrl, {headers: headers})
            .toPromise()
            .then(res => res.json())
            .catch(err => {
                return Promise.reject(err.json().error  || 'Server error');
            });
    }
}

Make a note of some of the following in above code:

  • The HTTP service get method returns an Observable object.
  • On an Observable object, RxJS toPromise() method is called which converts the observable to Promise object.
  • On the Promise object, the method then is invoked which returns the Promise<Rx[]>.

The code below represents the processing of callee method which returns Promise<Rx[]>.

export class RxListComponent  implements OnInit {
  rxlist: Rx[];
  errorMessage: string;

  constructor(private rxService: RxService, private router: Router) {
    this.errorMessage = '';
  }

  ngOnInit(): void {
    this.getRx();
  }

  getRx() {
    this.rxService.getRx()
    .then(rxlist => {
        this.rxlist = rxlist;
        if (this.rxlist.length === 0) {
          this.errorMessage = 'There are no prescriptions you have created so far!';
        }
      },
      error =&amp;gt;  {
        this.router.navigateByUrl('/auth/login');
        console.error('An error occurred in retrieving rx list, navigating to login: ', error);
      });
  }
}

Promise & Angular HttpClient Service

In this section, you will learn the usage of Promise with Angular HttpClient service. The code given below works for Angular 4.3 and Angular 5 apps. Note that HttpClient is the recommended way for communicating with remote APIs from Angular 5.* onwards.

Make a note of some of the following in the code given below:

  • API toPromise() is used to convert Observable response (HttpResponse<object>) object to Promise response object.
  • HttpHeaders instance is used to set the Authorization information in the outgoing interest.
  • Option ‘observe’: response makes sure entire Http response is returned in the response including data and headers information.
  • Promise.reject is used when promise state moves to rejected.
import {Http, Headers, RequestOptions} from '@angular/http';
import {Injectable} from '@angular/core';
import {Rx} from './rx';
import {Observable} from 'rxjs/Observable';
import {Cookie} from 'ng2-cookies';
import {HttpClient, HttpHeaders, HttpResponse} from "@angular/common/http";

@Injectable()
export class RxService {
    private rxUrl = 'http://localhost:8080/rx';

    constructor(private httpClient: HttpClient) {
    }

    getRx(): Promise<Rx[]> {
        return this.httpClient.get(this.rxUrl, {observe: 'response', headers:  new HttpHeaders().set('Authorization', 'Bearer ' + Cookie.get('access_token'))})
            .toPromise()
            .then(this.extractData)
            .catch(err => {
                return Promise.reject(err.error || 'Server error');
            });
    }

    extractData(res: HttpResponse<Object>) {
      var array = new Array();
      var key, count = 0;
      for(key in res.body) {
          array.push(res.body[count++]);
      }
      return array;
    }
}

Sample Interview Questions

  • What is a Promise in Javascript?
  • How to create and return a promise? Explain with a code example?
  • How is a returned promise object processed? Show with a code example?
  • Explain Http Get API implementation with Promise with a code example?
  • Explain HttpClient Get API implementation with Promise with a code example?
  • Explain the difference between Promise implementations for Http Get and HttpClient Get APIs?

Practice Test

Promise helps in achieving which of the following type of operations?

Which of the following is recommended service for communicating with remote server APIs from Angular 5.* onwards?

Angular Http or HttpClient Get API returns which of the following?

Angular HttpClient forms part of which of the following library?

Which of the following are possible states of Promise execution?

Further Reading

Summary

In this post, you learnt about some of the following:

  • Terminologies and concepts related with Promise concept in Javascript
  • How is Promise concept used in Angular vis-a-vis Angular 4/Angular 2 Http service and Angular 5 HttpClient service.
  • Sample interview questions
  • Practice tests to check your knowledge

Did you find this article useful? Do you have any questions about this article or understanding Promise and related concepts and terminologies vis-a-vis Angular 4/Angular 2 Http APIs and Angular 5 HttpClient APIs? Leave a comment and ask your questions and I shall do my best to address your queries.

Ajitesh Kumar

Ajitesh Kumar

Ajitesh has been recently working in the area of AI and machine learning. Currently, his research area includes Safe & Quality AI. In addition, he is also passionate about various different technologies including programming languages such as Java/JEE, Javascript and technologies such as Blockchain, mobile computing, cloud-native technologies, application security, cloud computing platforms, big data etc.

He has also authored the book, Building Web Apps with Spring 5 and Angular.
Ajitesh Kumar

Leave A Reply

Time limit is exhausted. Please reload the CAPTCHA.