Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video.
Perform Cleanup With finally()2:47 with Guil Hernandez
The `finally()` method is a new addition to promises. It gets called once a promise is fully settled, regardless of whether it's fulfilled or rejected. Finally is useful when you need to do some clean up after the promise sequence finished.
So now I want to teach you a third method that's a newer addition to Promises. 0:00 It's called finally. 0:04 And it gets called once a promise is fully settled. 0:06 Meaning, regardless of whether the promise is fulfilled or rejected, 0:09 the callback function passed to it gets executed. 0:13 Because of this, it's usually best to use finally as the last chain method. 0:16 And finally is useful if and 0:22 when you need to do some clean up after the promise sequence finished. 0:23 For example, when the button is clicked, I want to change the button's text to 0:27 loading, then remove the button from the page once all the data is returned. 0:32 So first in the EventListener I'll set the text content 0:37 of the button on click with event.target.textContent = Loading. 0:42 Then chain the finally method to the end of the Promise sequence. 0:52 Finally takes a function that's called when the promise is settled. 0:59 So next I'll pass the code that removes the button from the page, 1:03 event.target.remove into the finally method using an arrow function. 1:09 In the browser, click the button and see the text change to Loading. 1:16 Then it's removed from the page when the data loads. 1:21 The finally method removes the button from the page after the data is fetched and 1:23 processed, regardless of whether or not that operation succeeded. 1:28 Because of that, if an error occurs, for example, 1:32 users may see a blank section of content like this. 1:36 So we can use catch to display a user-friendly message to let them 1:40 know something went wrong. 1:44 For instance, in the catch method, I'll open up a set of curly braces, 1:46 since we're going to pass it multiple lines of code. 1:52 Then I'll set the innerHTML of the main peopleList div, 1:56 To display an h3 with the text, something went wrong. 2:04 So now this message is going to appear on the page in the event of an error, 2:12 like a connectivity issue or a rejected promise. 2:18 So as you've learned so far, promises offer a more intuitive flow. 2:22 Whereas callback nesting requires you to jump around to comprehend the code's flow, 2:27 promises let you chain then methods to achieve sequential tasks, 2:32 providing a more linear reading experience. 2:36 Be sure to review the teacher's notes with this video to see more examples of how to 2:39 run multiple promises in parallel with promise.all 2:43
You need to sign up for Treehouse in order to download course files.Sign up