# What a Promise is in Angular ?

In 
Published 2022-12-03

This tutorial explains to you what a promise is in Angular and also provide you with an example.

In Angular, sometime we need to use the following approach: run a ASYNC code, and function of an event (in that code) run the CODE-A or CODE-B (generally when an error occurs). This is an improvement of a Callback function in Angular. Using a Callback function, you will run something after a ASYNC call.

Take a look at the following example:

child1.component.ts
/* This is child1.component.ts file */
 
import { Component, OnInit } from '@angular/core';
 
@Component({
  selector: 'app-child1',
  templateUrl: './child1.component.html',
  styleUrls: ['./child1.component.css']
})
export class Child1Component implements OnInit {
 
  constructor() { }
 
  ngOnInit() {
 
    let promise = new Promise((resolve1, reject1) => {
      // Do some ASYNC stuff
       
      if (this.functionNr2() == 'OK') {
          resolve1('OK');
      } else {
          reject1('There are some problems ...');
      }
  
    }).then(
      (data1) => { 
         console.log('OK - from then 1');
         console.log(data1); 
        },
      (err1) => { 
         console.log('ERROR - from then 1');
         console.log(err1);
         }
      );
 
  }
   
  functionNr2():string {
  
    var num:number = 0
    var count1:number = 0;
    var count:number = 0;
  
    console.log("START: functionNr2 ["+new Date()+"]");
    for(num=0;num<=300000000;num++) {
       if (num % 2 == 0) {
        count1 = count1 + 2;
       }
       if (num % 3 == 0) {
        count1 = count1 + 2;
       }
       if (num % 4 == 0) {
        count1 = count1 - 2;
       }
       count++;
    }
    console.log("END: functionNr2 ["+new Date()+"]");
  
    return 'nOK';
  }
}

And here is the output in the console when code completed:

Take a look at the following example:

child1.component.ts file
/* This is child1.component.ts file */
 
import { Component, OnInit } from '@angular/core';
 
@Component({
  selector: 'app-child1',
  templateUrl: './child1.component.html',
  styleUrls: ['./child1.component.css']
})
export class Child1Component implements OnInit {
 
  constructor() { }
 
  ngOnInit() {
 
    let promise = new Promise((resolve1, reject1) => {
      // Do some ASYNC stuff
       
      if (this.functionNr2() == 'OK') {
          resolve1('OK');
      } else {
          reject1('There are some problems ...');
      }
  
    }).then(
      (data1) => { 
         console.log('OK - from then 1');
         console.log(data1); 
        },
      (err1) => { 
         console.log('ERROR - from then 1');
         console.log(err1);
         //throw new Error("fail");
         }
      )
      .then(
        (data1) => { 
           console.log('OK - from then 2');
          },
        (err1) => { 
           console.log('ERROR - from then 2');
           }
        );
 
  }
   
  functionNr2():string {
  
    var num:number = 0
    var count1:number = 0;
    var count:number = 0;
  
    console.log("START: functionNr2 ["+new Date()+"]");
    for(num=0;num<=300000000;num++) {
       if (num % 2 == 0) {
        count1 = count1 + 2;
       }
       if (num % 3 == 0) {
        count1 = count1 + 2;
       }
       if (num % 4 == 0) {
        count1 = count1 - 2;
       }
       count++;
    }
    console.log("END: functionNr2 ["+new Date()+"]");
  
    return 'nOK';
  }
}

And here is the output in the console when code completed:

Here are some remarks on the code above:

  • the functionNr2() simulate a ASYNC code;

  • you can use "then" keyword in order to execute some code after the promise return;

  • you can have maximum 2 procedures/ function you can run after a promise return a value (for completed without or with error cases);

  • you can have more than one "then" keyword used with a promise;

  • you can use throw new Error("fail") command, if you want to generate an error (for testing purpose);

  • At any time, a promise can be in one of these three states:

    1. pending (when functionNr2() is running in my case)
    2. fulfilled (when functionNr2() returns "OK" in my case: a promise is considered fulfilled or resolved)
    3. rejected (when functionNr2() returns something that is not "OK" in my case: a promise is NOT considered fulfilled or resolved, so is rejected)
  • "then" keyword can be used to handle errors:

    .then((data) => { console.log(data); })

    .then(undefined, (error) => { console.log(error); });

  • you can use "catch" keyword much better to do the same thing:

    .then((data) => { console.log(data); })

    .catch((error) => { console.log(error); });

  • You can use Promise.all([firstPromise, secondPromise, thirdPromise]) feature in order the see if all promises are fulfilled. If one is rejected, Promise.all is rejected.

  • You can use Promise.race([firstPromise, secondPromise, thirdPromise]) feature in order the see the result of the promise which will give you a response first.