Why would the loading indicator stay active if the promise was settled?
Problem Description:
I was reading this article about Promise Basics on Javascript.info and came across an example about a usecase for the .finally()
method.
It says:
The idea of finally is to set up a handler for performing cleanup/finalizing after the previous operations are complete.
E.g. stopping loading indicators, closing no longer needed connections, etc.
I’m not sure about the implementation of a loading indicator, but I assume this example doesn’t jump to conclusions.
So assuming that I have some loading indicator that waits for some promise to settle, then it gets settled. Why would the loading indicator stay active if the promise was settled then?
It’s just an abstract question.
Solution – 1
.finally()
is just a way to run some code when the promise either resolves or rejects. So, in a loading indicator, you probably need to clear the loading indicator whenever the operation is complete, whether it succeeded or not. That makes it an appropriate candidate to use .finally()
.
Keep in mind that .finally()
is just a programming convenience. You could put the same code in both a .then()
and a .catch()
and handle both outcomes that way too. Or, you could pass two handlers to .then()
. But, by putting it in a .finally()
handler, you only have to put it one place and it will run for either a resolve or reject outcome.
Solution – 2
The hypothetical loading indicator it discusses is one controlled by the author’s code.
const loading = document.createElement('img');
loading.src="loading.gif";
loading.alt="Loading!";
document.body.append(loading);
do_something().finally(() => loading.remove());
It wouldn’t disappear without you writing code to make it disappear because JavaScript does only what you tell it to do.
Solution – 3
Consider a form submission scenario,
We set the isLoading
to true, showing the loading indicator on submission.
On Successful submission, then()
-> We need to stop the loading indicator.
On Failure/Errors after submission, catch()
-> We need to stop the loading indicator, to allow the user to re-edit the form and submit again.
So, we place it in finally()
to set isLoading
to false for both scenarios. As the code placed in finally will run regardless of resolve/reject.