logo
post image

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

The finally() callback of the Promise object can be used to know whether the Promise was settled - either 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
	});