0

How to do a proper finally on a promise?

Can I add a finally equivalent to this?

functionReturningPromise()
   .then(success => {})
   .catch(error => {})

or should I do it this way (does this even work as expected)?

functionReturningPromise()
   .then(success => {},error => {}).then(() => { /* finally code */ })
Schneyer
  • 1,197
  • 1
  • 9
  • 27

3 Answers3

2

You can use

.finally()

Example:

functionReturningPromise()
.then(data=>console.log(data))
.catch(error=>console.log(error))
.finally(()=>console.log("FINISH"))

The finally is called allways

0

You can do this in two ways:

  1. Use finally from Promise.prototype.finally()
yourPromiseFunction
  .then(function(json) { /* process your JSON further */ })
  .catch(function(error) { console.log(error); /* this line can also throw, e.g. when console = {} */ })
  .finally(function() { console.log("finally") });
  1. Or you can add an additional then() after the catch() to do finally in all the browsers.

Example:

yourPromiseFunction.then(() => console.log('Resolved'))
            .catch(() => console.log('Failed'))
            .then(() => console.log('This is your finally'));
Avanthika
  • 3,984
  • 1
  • 12
  • 19
0

Yes, finally works with promises.

Example:

let isLoading = true;

fetch(myRequest).then(function(response) {
        var contentType = response.headers.get("content-type");
        if (contentType && contentType.includes("application/json")) {
            return response.json();
        }
        throw new TypeError("Oops, we haven't got JSON!");
    })
    .then(function(json) {
        /* process your JSON further */
    })
    .catch(function(error) {
        console.log(error); /* this line can also throw, e.g. when console = {} */
    })
    .finally(function() {
        isLoading = false;
    });

For further reference refer https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/finally

Dheeraj Gupta
  • 649
  • 6
  • 10