Angular Promise is used to perform asynchronous operation that use operation states to completes or fails. A promise execution process have the following four states.
Below image you can see a simple promise execution process.
As you can see at above image initial state is pending state. After start execution,
Syntax
new Promise(executor);
Sample Example
We have define promose with sample example as following:
Here, Resolved defines the .Then and reject defines Catch
There are few points which are useful to understand promise in better way.
1. Promise Not cancellable
2. Promise emits only single value at a time(having one pipeline)
The below example show that firstly we have create object of Promise and define the values First, Second and Third.
const SingleEmitPromise = new Promise((resolve, reject) => {
resolve('First');
resolve('Second');
resolve('Third');
});
SingleEmitPromise.then((value) => console.log('Promise -' + value));
The above example will produce single value at a time.
3. Promise starts immediately
Promise starts immediately so it is called eager also. When we create object of promise it will start immediately.
// Promise starts immediately
const startspromise = new Promise(() => console.log('Promise is called'));
The above example will starts immediately.
4. Promise Always asynchronous
Async/Await is used to work with promises in asynchronous functions.
async function asyncFun() {
let asyncPromise = new Promise((resolve, reject) => {
setTimeout(() => resolve("Promise is finished called"), 10000)
});
let promiseResult = await asyncPromise;
alert(promiseResult);
}
asyncFun();
In the above code, await keyword inside a async function blocks the execution in that function context until the promise it is awaiting is settled. This gives us clean syntax to work with promises in a synchronous fashion. When we run that function after wait some time alert message will looks like that:
5. Promises with TypeScript and Angular
Let's now see how to use Promises in Angular to work with HTTP asynchronously. we will learn that with a example.
import { Component } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient } from "@angular/common/http";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'PromiseApp';
constructor(private httpClient: HttpClient) {
}
ngOnInit() {
this.fetchDataAsPromise()
.then((data) => {
console.log(JSON.stringify(data));
})
.catch((error) => {
console.log("Promise rejected with " + JSON.stringify(error));
});
}
fetchDataAsPromise() {
return this.httpClient
.get(
'https://localhost:44340/api/employee'
).toPromise();
}
}
Add the following code in App.Module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HttpClientModule, HttpClient } from "@angular/common/http";
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Now run the applicatyion and check browser console.
Now run the over all code to understand promise better way.
import { Component } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient } from "@angular/common/http";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'PromiseApp';
constructor(private httpClient: HttpClient) {
}
ngOnInit() {
// Simple Promise example
var promise = new Promise((resolve, reject) => {
resolve("Promise Resolved");
})
promise.then((success) => {
console.log(success);
})
.catch((error)=> {
console.log(error)
});
//Promise Emits a single value only
const SingleEmitPromise = new Promise((resolve, reject) => {
resolve('First');
resolve('Second');
resolve('Third');
});
SingleEmitPromise.then((value) => console.log('Promise -' + value));
// Promise starts immediately
const startspromise = new Promise(() => console.log('Promise is called'));
// Promise Not cancellable
//No rxjs support for operators.
// Promise Always asynchronous
async function asyncFun() {
let asyncPromise = new Promise((resolve, reject) => {
setTimeout(() => resolve("Promise is finished called"), 10000)
});
let promiseResult = await asyncPromise;
alert(promiseResult);
}
asyncFun();
this.fetchDataAsPromise()
.then((data) => {
console.log(JSON.stringify(data));
})
}
fetchDataAsPromise() {
return this.httpClient
.get(
'https://localhost:44340/api/employee'
).toPromise();
}
}
Output