Combine Async/Await with Promises2:31 with Guil Hernandez
Async/await is not meant to replace promises -- it's actually syntactic sugar for creating functions that return and wait for promises. In this video, you'll learn how to use a combination of promises and async/await to produce code that's more readable.
In the previous video, 0:00 you learned how async-await simplifies the process of working with promises. 0:01 You are able to write you asynchronous code in a way that resembles synchronous 0:05 code, which in some ways might enhance the readability and flow of your code. 0:09 An async is just a function that returns a promise, whether you use a wait or not. 0:12 To demonstrate, I'll quickly comment out everything inside the getPeopleInSpace 0:19 function, including the await operations. 0:23 Then console.log the function call to getPeopleInSpace. 0:26 In the console, you can see that the function still returns a promise object, 0:31 whose PromiseStatus is resolved and it's PromiseValue is undefined. 0:35 Now if the function returns a literal value, like the URL passed to it, 0:39 for example, you'll see it returned as the PromiseValue. 0:44 And if I uncomment the code inside the function, 0:49 you'll see the array of objects as the PromiseValue. 0:53 So because in async function always returns a promise, 0:57 it means that we're able to combine async-await with traditional promises. 1:00 Now async-await is not meant to replace promises. 1:06 Rather, it's syntactic sugar for creating functions that return and wait for 1:09 promises. 1:14 So really it's a supplement to promises. 1:15 So now I'll teach you how to use a combination of promises and 1:17 async-await to produce code that might be a little more readable. 1:21 We can call then, catch, 1:25 and finally on getPeopleInSpace to handle its return promise. 1:26 For example, I'll delete the astros variable and the await keyword, and 1:31 chain a then method onto getPeopleInSpace and pass it a reference to generate HTML. 1:37 Now we can delete the call to generate HTML. 1:44 And next, I'll chain the finally method to remove the button from the page 1:48 after the data is fetched and processed. 1:53 Like earlier, I'll pass finally a function that returns event.target.remove. 1:56 This function no longer makes use of the await keyword, so I can delete 2:08 the keyword async from the callback, and this is going to work just like before. 2:13 Now to me, the code in the event listener feels more readable and 2:21 makes the flow of the program a little bit clearer. 2:25
You need to sign up for Treehouse in order to download course files.Sign up