The finally() method of a Promise object schedules a function to be called when the promise is settled (either fulfilled or rejected). It immediately returns an equivalent Promise object, allowing you to chain calls to other promise methods. This lets you avoid duplicating code in both the promise's then() and catch() handlers.

    
    function checkMail() {
      return new Promise((resolve, reject) => {
        if (Math.random() > 0.5) {
          resolve('Mail has arrived');
        } else {
          reject(new Error('Failed to arrive'));
        }
      });
    }

    checkMail()
      .then((mail) => {
        console.log(mail);
      })
      .catch((err) => {
        console.error(err);
      })
      .finally(() => {
        console.log('Experiment completed');
      });