Promise – finally

The finally method of a Promise  allows you to execute code after a promise has been settled. If the promise succeeds or fails the finally method is called. This is useful if you want to run some code regardless of the outcome of the promise. The promise finally method is similar to the finally method in a try catch finally block.


Its supported on most browsers, you can find the full list here . There are a few ployfills like this available. 


you can call the finally method on the promise object or you can chain it with a then and catch methods

var promise = new Promise((resolve, reject)=>resolve(true))
//Attach finally method directly to promise
//Chain finally

In the above code snippets, we first create a promise object, then we show the two ways to use the finally method, by attaching it directly to the promise or by chaining it. 


In this example, consider that we are logging in a user, we need to fetch the profile image of the user and if they don’t have a profile, we assign them a default profile image and then take them to the home page

Example 1

user.img = img;
user.img = defaultProfileImg;

Example 2

user.img = img;
user.img = defaultProfileImg;

In example 1, use don’t use the finally block, so we have to repeat code to go to the home page in the then and the catch block.

In example 2, we use the finally block so need to call the goToHome code only once

Share this!

Leave a Reply

Your email address will not be published. Required fields are marked *