ECMAScript question detail
Promise finally
Sometimes you may need to avoid duplicate code in the then() and catch() methods.
myPromise
.then(result => {
// process the result and then clean up the resources
})
.catch(error => {
// handle the error and then clean up the resources
});
The finally() method is useful if you want to do some processing or resource cleanup once the promise is settled(i.e either fulfilled or rejected).
Let's take a below example to hide the loading spinner after the data is fetched and processed.
let isLoading = true;
fetch('http://somesite.com/users')
.then(data => data.json())
.catch(err => console.error(err))
.finally(() => {
isLoading = false;
console.log('Finished loading!!');
})