๐Ÿฟ 2 min. read

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

Monica Powell

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.

1fetch("https://dog.ceo/api/breeds/image/random")
2 // handle successful response
3 .then(response => response.json())
4 .then(json =>
5 this.setState(
6 {
7 imgUrl: json.message,
8 },
9 () => {}
10 )
11 )
12 // if there's an error log it!
13 .catch(err => console.log(err))
14 // once promise resolves loading should be set to false
15 // regardless of if data was returned or if there was an error
16 .finally(() => this.setState({ loading: false }))

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

This article was published on February 25, 2020.


Don't be a stranger! ๐Ÿ‘‹๐Ÿพ

Thanks for reading "Finally(), I'll clean up my Promises!". Join my mailing list to be the first to receive my newest web development content, my thoughts on the web and learn about exclusive opportunities.

    ย 

    I wonโ€™t send you spam. Unsubscribe at any time.