In JavaScript, the finally function of the Promise object invokes a callback once a promise has been settled.
The Promise.finally method in JavaScript triggers a callback function regardless of whether the promise is fulfilled or rejected, and it is commonly utilized for performing cleanup operations.
In straightforward terms, the finally method associated with Promise instances arranges for a function to execute once the promise has been settled, regardless of whether it is resolved or rejected. This method promptly returns a new Promise object, enabling the chaining of additional calls to other promise methods.
Syntax
Promise.finally(settled())
Parameters
- Settled: This refers to a function that is invoked when the promise reaches a settled state, either being fulfilled or rejected.
- Return value: The function returns a Promise that has its finally handler established to the given function.
Example
let promise = new Promise((resolve, reject) => {
resolve("Done!");
});
promise
.then((result) => {
console.log(result);
})
.finally(() => {
console.log("This runs no matter what.");
});
Output:
Done!
This runs no matter what.
How does Finally Work in JavaScript?
A try-catch construct is invariably accompanied by a finally block. It is possible to utilize only the try statement or a combination of the try statement along with catch and finally blocks. The code that is meant to be executed may encounter an error after the execution of these blocks.
This error could arise from either a coding error or a runtime problem. The catch block will activate when the operations within the try block encounter a failure.
In the event of a failure, the catch block enables the necessary response to be executed. The finally block is guaranteed to run regardless of whether the try or catch blocks are executed. When implementing a try statement, it is essential to include at least one of the catch or finally blocks; however, it is not mandatory to have both.
Examples of Promise.finally
Example 1
new Promise((resolve, reject) => {
setTimeout(() => resolve("Data loaded"), 1000);
})
.then(result => {
console.log("Success:", result);
})
.catch(error => {
console.log("Error:", error);
})
.finally(() => {
console.log("Operation complete");
});
Output:
Success: Data loaded
Operation complete
Explanation
In this snippet, a new Promise is instantiated that completes successfully after a delay of 1 second, providing the message “Data loaded.”
The then function is utilized to manage the data that has been successfully resolved, which is subsequently displayed in the console accompanied by a confirmation message.
The catch function serves the purpose of managing any potential errors that may arise, and these errors are recorded in the console accompanied by an error message.
The finally method is utilized to run a callback function irrespective of the outcome of the promise, whether it has been fulfilled or rejected.
Example 2
//cleanup after timeout
function delayedAction() {
return new Promise((resolve) => {
setTimeout(() => {
resolve("Done after delay");
}, 1000);
});
}
delayedAction()
.then(msg => {
console.log(msg);
})
.finally(() => {
console.log("Clearing temporary data...");
});
Output:
Done after delay
Clearing temporary data…
Explanation
In this code snippet, the finally method is utilized to perform a clean-up operation once a promise has been resolved or rejected.
Example 3
//Simulating loading with setTimeout
function loadData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Data received!");
}, 2000);
});
}
loadData()
.then((data) => {
console.log(data);
})
.finally(() => {
console.log("Cleanup: hiding loading spinner...");
});
Output:
Data received!
Cleanup: hiding loading spinner...
Explanation
In the provided code, the loadData function yields a Promise that fulfills after a duration of 2 seconds, thereby emulating a loading operation.
The then method serves to manage the data that has been resolved, and this information is subsequently printed to the console.
The finally method serves the purpose of executing a cleanup task (such as concealing a loading spinner) irrespective of whether the operation succeeded or failed.