Saturday, November 16, 2024
Google search engine
HomeLanguagesJavascriptJavaScript Promise finally() Method

JavaScript Promise finally() Method

The finally() method of the Promise object is used to return a Promise when a Promise is settled, that is, it is either fulfilled or rejected. A Promise is a JavaScript object which generates a value after an asynchronous function executes successfully. When it does not execute successfully due to a timeout, then it generates an error.

It can be used to perform cleanup tasks once the promise is settled as it is always executed irrespective of whether the promise is fulfilled or rejected. It also prevents the duplication of code in the then() and catch() methods of the Promise.

Syntax:

task.finally(function() {
  // Task to be performed when
  // the promise is settled 
});

Parameters: This method has a single parameter as mentioned above and described below:

  • onFinally: It is the function that will be called when the Promise is settled.

Return Value: It returns a Promise whose finally handler is set to the specified function.

The below example demonstrates the finally() method:

Example:

Javascript




// Define the Promise
let task = new Promise((resolve, reject) => {
  setTimeout(() => {
  
    // Reject the Promise
    reject("Promise has been rejected!");
  }, 2000);
});
  
task
  .then(
    (data) => {
      console.log(data);
    },
  
    // Handle any error
    (error) => {
      console.log("Error:", error);
    }
  )
  
  // Specify the code to be executed 
  // after the Promise is settled
  .finally(() => {
    console.log(
      "This is finally() block that is " +
      "executed after Promise is settled"
    );
  });


Output:

Error: Promise has been rejected!
This is finally() block that is executed after Promise is settled
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments