Finally(), I'll clean up my Promises!

Monica Powell
February 25, 2020

When handling asynchronous operations sometimes it is necessary to update the state after the promise resolves regardless of it was successful or rejected. In order to avoid having to duplicate this cleanup code there's a handy method, finally() that has a callback function that is executed once a promise settles by either being fulfilled or rejected. So if for example you want to update the loading state from true to false after a promise settles regardless of the response was an error or not you can do something like.

fetch("https://dog.ceo/api/breeds/image/random")
    // handle successful response
   .then(response => response.json()) 
   .then(json =>
     this.setState(
       {
         imgUrl: json.message
       },
       () => {}
     )
   )
   // if there's an error log it!
   .catch(err => console.log(err))
   // once promise resolves loading should be set to false
   // regardless of if data was returned or if there was an error
   .finally(()=> this.setState({loading: false})); 

Learn more at: Promise.prototype.finally() - JavaScript | MDN

If you learned something from reading "Finally(), I'll clean up my Promises!" consider sharing it.
LinkedIn

Hi, I'm Monica! I'm a Full Stack Engineer who is currently building technology to bring people together IRL at Meetup and focusing on growing the React Ladies community for women + non-binary React developers. I'm interested in discussing React, JAMStack, open-source, tech inclusion, automation and more. 🍿