Execute Cleanup Logic in a JavaScript Promise Chain with Promise.prototype.finally()

Share this video with your friends

Send Tweet

The Promise.prototype.finally() method lets you attach a callback to a JavaScript promise that is executed once that promise is settled, whether fulfilled or rejected. It is typically used to perform cleanup logic (such as hiding loading spinners, freeing used resources, …). By using finally(), you don't have to duplicate that cleanup logic in both the promise’s fulfillment and rejection handlers.

Rion
Rion
~ 6 years ago

:( === "frowny face" ... :)

Philip John
Philip John
~ 6 years ago

why in codesandbox you have return films.slice() but not in the videos?

Marius Schulz
Marius Schulz(instructor)
~ 6 years ago

@Philip: Good catch! Unfortunately, I only realized that I should've added .slice() after recording most of the course, which is why it's in the code example, but not in the videos.

So why do we need .slice() at all? The getFilmTitles() function should be a pure function, which means it shouldn't mutate its parameters. However calling .sort() on an array will sort the array in-place rather than returning a new array in which all elements are sorted. By calling .slice() first, we create a new array which is then mutated in place. This is fine because we're no longer changing the films parameter.

This is not an issue in the code shown in this lesson because we're sorting the films array that we just got back from response.json() — nobody else is referencing it. Still, the getFilmTitles method was intended to be a pure function, so I've fixed it in the code examples.