As developers, we often find ourselves dealing with asynchronous operations in JavaScript, whether it’s fetching data from an API, interacting with the file system, or handling user events. While promises have greatly simplified the management of asynchronous code, there are still scenarios where we need to perform cleanup operations regardless of whether the promise is fulfilled or rejected.
This is where Promise.finally()
comes into play, offering an elegant solution for executing code after a promise has settled. Before we dive into the details, let's set the stage with a practical example. Imagine you're building a web application that fetches data from an external API.
During the fetching process, you might want to display a loading indicator to the user. Once the data is retrieved (or an error occurs), you'll want to hide the loading indicator. This is a perfect use case for Promise.finally()
.
function fetchData() {
showLoadingIndicator();
fetch('/api/data')
.then(response => response.json())
.then(data => {
// Process the fetched data
console.log(data);
})
.catch(error => {
// Handle any…