Computer >> Computer tutorials >  >> Programming >> Javascript

How to use finally on promise with then and catch in Javascript?


When a promise is settled, i.e either fulfilled or rejected, the specified callback function in finally method is invoked. The finally() method also returns a Promise.

This provides a way for code to be run whether the promise was fulfilled successfully or rejected once the Promise has been dealt with. Let us look at an example,

Example

new Promise(
   (resolve) => setTimeout(resolve("success"), 1000)
).then(val => console.log(val)).finally(() => console.log("Promise complete!"))

Output

success
Promise complete!

Now let us look what happens if a promise fails −

Example

// No method get on undefined. This will throw an error
new Promise(() => undefined.get())
   .then(val => console.log(val))
   .catch(err => console.log("Failed!"))
   .finally(() => console.log("Promise complete!"))

Output

Failed! 
Promise complete!

Note in both the cases whether failed or succeeded, the promise executed the finally statement.