Promise API allows you to execute Asynchronous operations. Promise executes one of the callback methods, i.e either resolve or reject. Sometimes you want to execute code inside irrespective of resolving or rejecting callbacks.

Es9 introduced the finally feature to execute let’s create a Promise object

let promise1 = new Promise(function(resolve, reject) {
resolve("Resolved"); // Returns "Resolved" immediately
});

let promise2 = new Promise(function(resolve, reject) {
reject("Rejected"); // Returns "Rejected" immediately
});

The promise is called using the below code. promise1 returns and calls a resolved callback. promise2 returns and calls a rejected callback. then calls with resolved and rejected callbacks.

promise1.then(
function(result) { console.log(result)},
function(error) { console.log(error)}
);


promise2.then(
function(result) { console.log(result)},
function(error) { console.log(error)}
);

Output:

Resolved
Rejected

Similarly, you can rewrite then with then and catch as given below. catch used to catch rejected callbacks.

promise1
.then(function (result) { console.log(result) })
.catch(function (error) { console.log(error) });


promise2
.then(function (result) { console.log(result) })
.catch(function (error) { console.log(error) });

Javascript Promise finally method examples

ES09 introduced finally a method to promise API objects similar to the then method.

Syntax

promise.then(callback).catch(callback).finally(callback)

Example:

promise1.then(
function(result) { console.log(result)},
function(error) { console.log(error)}
).finally(function(){console.log("finally")});


promise2.then(
function(result) { console.log(result)},
function(error) { console.log(error)}
).finally(function(){console.log("finally")});

Similarly, the Above, can be rewritten using given below code

promise1
.then(function (result) { console.log(result) })
.catch(function (error) { console.log(error) })
.finally(function () { console.log("finally") });


promise2
.then(function (result) { console.log(result) })
.catch(function (error) { console.log(error) })
.finally(function () { console.log("finally") });

Output:

Resolved
Rejected
finally
finally

Hence, finally used to execute the clean-up code during asynchronous operation.