๐ฟ 2 min. read
Finally(), I'll clean up my Promises!
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 response3 .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 false15 // regardless of if data was returned or if there was an error16 .finally(() => this.setState({ loading: false }))
Learn more at: Promise.prototype.finally() - JavaScript | MDN
This article was published on February 25, 2020.