Angular Js

How to use Promise in Angular?

How to use Promise in Angular?

How to use Promise in Angular?

This Article helps you to Understand, How to use Promise in Angular?


What's a Promise in JavaScript?

A promise is an API abstraction in JavaScript that enables synchronous handling of asynchronous operations.

Imagine you wish to work with some data that was obtained from a distant server. Instead of waiting for the data to be fetched, we may establish a promise that takes care of the problem and lets the app continue doing other actions as this is an asynchronous operation (i.e., your code don't needs to wait for the server response before it can continue with its execution).

The promise will know what to do with data when it is fetched. This is similar to callbacks but promises have a better API and features.


How to create a Promise?

A promise can be made using a simple JavaScript API made available since ES6 or JavaScript 2015. Here is an example of a straightforward promise object that delivers I'll be back with you in a split second!


var promise = new Promise(function(resolve, reject) {
  setTimeout(function() {
    resolve('I promise to return this after 1 second!');
  }, 1000);
});

promise.then(function(value) {
  console.log(value);
});

You first build a Promise instance and give the executor function two arguments: resolve and refuse. You place your asynchronous code in the function's body. Here, a straightforward timeout function settles the promise after a second.

You must call the resolve() function after your asynchronous code has successfully executed. This function accepts as an argument either nothing or a value that needs to be returned, if any. If something goes wrong, you should instead use the reject() method, which accepts values such as the error that happened.

You must invoke the then() method of the promise after making an instance of it and passing a callback function as a parameter. As soon as the promise is fulfilled, this function will be called. Another function that will be invoked when the promise is denied can be passed as the second parameter to the then() method.

The promise is resolved or rejected when the resolve and reject functions are called. The resolve function is called after the executor function has called some asynchronous code, which either resolves the promise or rejects it if an error occurred.


A Promise can be in one of the following states:

  • pending: this is the initial state, neither fulfilled nor rejected.
  • fulfilled: the operation completed successfully.
  • rejected: the operation failed.


The Promise object has the following methods:

  • Promise.prototype.catch():
  • Promise.prototype.finally()
  • Promise.prototype.then():
  • Promise.all(): It wait for all promises to be resolved, or for any to be rejected
  • Promise.allSettled(): It wait until all promises have settled (each may resolve, or reject).
  • Promise.race(): It waits until any of the promises is resolved or rejected.
  • Promise.reject(): It returns a new Promise object that is rejected with the given reason
  • Promise.resolve(): It returns a new Promise object that is resolved with the given value.


Example 1: calling external API


//app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpClientModule }  from '@angular/common/http';

import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';

@NgModule({
  imports:      [ BrowserModule, FormsModule, HttpClientModule ],
  declarations: [ AppComponent, HelloComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }





//app.component.ts
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit  {
  name = 'Angular';
  apiUrl = 'https://www.thetechfoyer.com/api/data.json';

  constructor(private httpClient: HttpClient){}

  ngOnInit(){
    this.fetchData();
  }

  private fetchData(){
    //We can send a GET HTTP request using the get() method which returns an RxJS
    //Observable but we can get a JavaScript Promise by using the toPromise() method
    //of Observable:
    //With our API URL, we call the get() method. From the received promise, we call
    //the toPromise() method to obtain a promise.
    const promise = this.httpClient.get(this.apiUrl).toPromise();
    console.log(promise);

    //The API request will not be sent until we call the then() method of the promise as
     promise.then((data)=>{
      console.log("Promise resolved with: " + JSON.stringify(data));
    }, (error)=>{
      console.log("Promise rejected with " + JSON.stringify(error));
    })
  }
 }

Promises can be consumed by registering functions using .then and .catch methods.
then() method takes two functions as parameters and it is invoked when a promise is either resolved or rejected.
You can see that the first function is executed if promise is resolved and a result is received and the Second function is executed if the promise is rejected and an error is received. It is optional and there is a better way to handle error using .catch() method just as shown below.




Example 2: With Resolve and Reject


search(term:string) {
  let promise = new Promise((resolve, reject) => {
    let apiURL = `${this.apiRoot}?term=${term}&limit=20`;
    this.http.get(apiURL)
      .toPromise()
      .then(
        res => { // Success
        this.results = res.json().results;
        resolve();
        },
        msg => { // Error
        reject(msg);
        }
      );
  });
  return promise;
}

We also call the resolve() and reject() functions above after we have finished processing the callback from external API, so the calling function gets notified and can perform any post processing.



Related Post

About Us

Community of IT Professionals

A Complete IT knowledgebase for any kind of Software Language, Development, Programming, Coding, Designing, Networking, Hardware and Digital Marketing.

Instagram