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

Monica Powell
February 25, 2020 🍿 2 min read

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

LinkedIn

Subscribe to Newsletter

Thanks for reading "Finally(), I'll clean up my Promises!". Consider joining my newsletter to receive messages about new content, my thoughts on the web and learn about exclusive opportunities.

     

    I won’t send you spam. Unsubscribe at any time.