Angular promise finally example
Promise API has then-and-catch methods to handle success and error callbacks. Suppose you want to execute a clean-up cod execute always in Promise execution. You can do multiple ways to execute
One way is to add polyfills, Another ways using Ecmascript2020(ES9), introduced finally block or method to execute irrespective of the promised result.
This post explains multiple things
- How to always run some code when a promise is fulfilled
- How to always run some code when a promise is rejected
finally used to clean the code that contains references, clean subscribe, and clear timeouts.
Angular application create
Let’s create an angular application using angular CLI
Check whether Angular CLI is installed or not using the below command.
ng version command gives an angular CLI installed version.
if it is not installed, install using npm install —location=global @angular-cli@latest command.
B:\blog\jswork>ng version
_ _ ____ _ ___
/ \ _ __ __ _ _ _| | __ _ _ __ / ___| | |_ _|
/ △ \ | '_ \ / _` | | | | |/ _` | '**| | | | | | |
/ \_** \| | | | (_| | |_| | | (\_| | | | |**_| |_** | |
/_/ \_\_| |_|\_\_, |\__,_|\_|\__,_|\_| \_**\_|\_\_\_**|**_|
|_**/
Angular CLI: 14.2.6
Node: 14.17.0
Package Manager: npm 8.12.0
OS: win32 x64
Angular:
...
## Package Version
@angular-devkit/architect 0.1402.6 (cli-only)
@angular-devkit/core 14.2.6 (cli-only)
@angular-devkit/schematics 14.2.6 (cli-only)
@schematics/angular 14.2.6 (cli-only)
Next, Create an angular application using the ng new command This command creates an angular application folder, required dependencies, and installs it.
B:\blog\jswork>ng new angular-latest-app
? Would you like to add Angular routing? No
? Which stylesheet format would you like to use? CSS
CREATE angular-latest-app/angular.json (2982 bytes)
CREATE angular-latest-app/package.json (1049 bytes)
CREATE angular-latest-app/README.md (1070 bytes)
CREATE angular-latest-app/tsconfig.json (863 bytes)
CREATE angular-latest-app/.editorconfig (274 bytes)
CREATE angular-latest-app/.gitignore (548 bytes)
CREATE angular-latest-app/.browserslistrc (600 bytes)
CREATE angular-latest-app/karma.conf.js (1435 bytes)
CREATE angular-latest-app/tsconfig.app.json (287 bytes)
CREATE angular-latest-app/tsconfig.spec.json (333 bytes)
CREATE angular-latest-app/.vscode/extensions.json (130 bytes)
CREATE angular-latest-app/.vscode/launch.json (474 bytes)
CREATE angular-latest-app/.vscode/tasks.json (938 bytes)
CREATE angular-latest-app/src/favicon.ico (948 bytes)
CREATE angular-latest-app/src/index.html (302 bytes)
CREATE angular-latest-app/src/main.ts (372 bytes)
CREATE angular-latest-app/src/polyfills.ts (2338 bytes)
CREATE angular-latest-app/src/styles.css (80 bytes)
CREATE angular-latest-app/src/test.ts (749 bytes)
CREATE angular-latest-app/src/assets/.gitkeep (0 bytes)
CREATE angular-latest-app/src/environments/environment.prod.ts (51 bytes)
CREATE angular-latest-app/src/environments/environment.ts (658 bytes)
CREATE angular-latest-app/src/app/app.module.ts (314 bytes)
CREATE angular-latest-app/src/app/app.component.html (23083 bytes)
CREATE angular-latest-app/src/app/app.component.spec.ts (992 bytes)
CREATE angular-latest-app/src/app/app.component.ts (222 bytes)
CREATE angular-latest-app/src/app/app.component.css (0 bytes)
√ Packages installed successfully.
The directory is already under version control. Skipping initialization of git.
Next, Change to the directory
B:\blog\jswork>cd angular-latest-app
Start the server using the ng serve command
B:\blog\jswork\angular-latest-app>ng serve
√ Browser application bundle generation complete.
Initial Chunk Files | Names | Raw Size
vendor.js | vendor | 1.77 MB |
polyfills.js | polyfills | 318.07 kB |
styles.css, styles.js | styles | 210.10 kB |
main.js | main | 48.07 kB |
runtime.js | runtime | 6.53 kB |
| Initial Total | 2.34 MB
Build at: 2022-10-15T05:20:51.373Z - Hash: da3a12fb5f9f1c4c - Time: 29039ms
** Angular Live Development Server is listening on localhost:4200, open your browser on <http://localhost:4200/> **
√ Compiled successfully.
√ Browser application bundle generation complete.
Initial Chunk Files | Names | Raw Size
main.js | main | 48.07 kB |
runtime.js | runtime | 6.53 kB |
3 unchanged chunks
Build at: 2022-10-15T05:23:42.252Z - Hash: 7074ff8b767e8aa8 - Time: 2682ms
Angular promise is finally an example
promise has the below methods already
- then: catch the resolved or rejected code
- catch: catch the error or rejected cases in Promise objects
what if an unhandled exception throws in a catch? finally used and called to handle the cleanup code or unhandled exceptions in promise.
In the below component, fetch used to call the jsonplaceholder REST API, returns the Promise object. added then and finally block. finally, the block executes irrespective of the promise result i.e either Rejected or Resolved. Here is an example code
import { Component, OnInit } from "@angular/core";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"],
})
export class AppComponent implements OnInit {
jsonObject: any;
constructor() {
//console.log(this.jsonObject["title"]);
}
ngOnInit() {
fetch("https://jsonplaceholder.typicode.com/photos")
.then((response) => response.json())
.then((json) => {
this.jsonObject = json;
console.log(this.jsonObject.map((t: any) => t["title"])); // <-- print here
})
.finally(() =>
console.log("finally called irrespective of promise result"),
);
}
}
``;