Promise – finally

Spread the love

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.

Support

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

Syntax

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
promise.finally(x=>console.log(x));
//Chain finally
promise.then(x=>console.log(x))
.catch(e=>console.error(e))
.finally(_=>console.log('done');

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. 

Example

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

getProfileImg(user).then(img=>{
user.img = img;
goToHomePage();
}).catch(e=>{
user.img = defaultProfileImg;
goToHomePage();
})

Example 2

getProfileImg(user).then(img=>{
user.img = img;
}).catch(e=>{
user.img = defaultProfileImg;
}).finally(_=>goToHomePage());

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