Knowing whether Promise is Completed (either Fulfilled or Rejected) with finally()

Use-Cases of this tutorial

  • Know if a Javascript Promise was finished — either resolved or rejected.
  • Know about the finally() callback of a Promise

The finally() callback can be used to know whether the Promise was settled. We don't care whether it was resolved or rejected.

Sometimes we would just like to know whether the Promise was either fulfilled or rejected, that is, we are not much interested in the outcome of the Promise. We just want to execute some code upon the settlement of the Promise.

We can use then() and catch() callbacks, but it would lead to repetition of the code.

some_promise
	.then(function(data) {
		alert('Settled');

		// now send an AJAX request
	})
	.catch(function(error) {
		alert('Settled');

		// now send an AJAX request
	});

To handle such cases there is the finally() callback. This will be called when the Promise got either fulfilled or rejected.

some_promise.finally(function() {
	alert('Settled');

	// now send an AJAX request
});

Note that finally() callback function will receive no parameters.

We can also chain all three callbacks — then() and catch() & finally().

some_promise
	.then(function(data) {
		// resolved
	})
	.catch(function(error) {
		// rejected
	})
	.finally(function() {
		// settled
	});
Checking if Multiple Promises are Completed in Javascript
Loading Comments