Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

finally block in angular 2 promise

I observe that In angular 2 there is no finally block for promise API

angular 1 :

 loadUsers() {
  fetch('/api/users').then((response) => {
    return response.json();
  }).then((data) => {
    this.users = data;
  }).catch((ex) => {
    console.error('Error fetching users', ex);
  }).finally(() => {
     this.userLoaded = true;
};

Assuming I have to do same thing in angular 2

How to add finally block in angular 2 promise , as of now there are only then & catch blocks available in angular 2. If not finally then is there any way to add cleanup code after execution of each method , where do i write code to do finally block activities ?

like image 393
Dmehro Avatar asked Nov 16 '16 21:11

Dmehro


People also ask

What does the finally () method on Promise do?

The finally() method of a Promise schedules a function, the callback function, to be called when the promise is settled. Like then() and catch() , it immediately returns an equivalent Promise object, allowing you to chain calls to another promise method, an operation called composition.

Does finally return a Promise?

The finally() method of the Promise object is used to return a Promise when a Promise is settled, that is, it is either fulfilled or rejected. A Promise is a JavaScript object which generates a value after an asynchronous function executes successfully.

Whats are promises in angular4?

What Is Promise in Angular? Promises in Angular provide an easy way to execute asynchronous functions that use callbacks, while emitting and completing (resolving or rejecting) one value at a time. When using an Angular Promise, you are enabled to emit a single event from the API.

Can we use Promise in angular?

Promises can be executed by calling the then() and catch() methods. The then() method takes two callback functions as parameters and is invoked when a promise is either resolved or rejected. The catch() method takes one callback function and is invoked when an error occurs.


3 Answers

The easiest way to do this is to use the promise.finally shim.

  • Add it with npm install --save promise.prototype.finally
  • Add the typings: npm install --save-dev @types/promise.prototype.finally
  • In your main class, before bootstrapping the application, add the following code:
import { shim } from 'promise.prototype.finally';
shim();

You should now be able to use finally on your promises.

like image 102
Tom Spencer Avatar answered Sep 24 '22 13:09

Tom Spencer


This is usually done using Promise.always. This takes one function, and adds a new .then on the promise that gives the same function for both success and fail states. If the function is not available in the given promise-based environment, it's pretty easy to polyfill in.

Promise.always = function(p, fn) {
  return p.then(fn, fn);
}

usage:

var prom = fetch('/api/users').then...
Promise.always(prom, () => {
  this.userLoaded = true;
});
return prom;
like image 43
Katana314 Avatar answered Sep 24 '22 13:09

Katana314


Modern solution in 2019-2020

First of all, you should avoid manually adding polyfills without a good reason for it, don't do it blindly because you've read it somewhere.

The problem you encounter has two sides: typing declarations and the implementation.

In order to use Promise.finally in your code without typing errors you should add es2018.promise to the lib option in your tsconfig.json file.

For modern projects you should use the following configuration (which is default in Angular 8):

{
  "compilerOptions": {
    …
    "lib": [
      "es2018",
      "dom"
    ]
  }
}

This will fix the typing errors you have in the editor.

Also, according to the docs and my observations the correct polyfill for Promise.finally will be added by the Angular compiler automatically, you don't have to install or add anything.

But, in general, you could add a polyfill (only if it is proven to be required) in ./src/polyfills.ts file using core-js library. Always try to use core-js instead of other libraries, cause it's an industry standard and it's used by Angular internally.

For example, Promise.finally polyfill could be added like this:

import 'core-js/features/promise/finally';


See more at core-js documentation.

Also, make sure to read browser-support and differential-loading articles of Angular documentation.

like image 41
Slava Fomin II Avatar answered Sep 22 '22 13:09

Slava Fomin II