![JavaScript: From First Steps to Professional](https://static.frontendmasters.com/assets/courses/2022-11-15-javascript-first-steps/thumb.webp)
Check out a free preview of the full JavaScript: From First Steps to Professional course
The "Using Await with Promises" Lesson is part of the full, JavaScript: From First Steps to Professional course featured in this preview video. Here's what you'd learn in this lesson:
Anjana demonstrates using the await operator to wait for a Promise and obtain its resulting value. If the await operator is not used, JavaScript will return the promise object without the value of the promise.
Transcript from the "Using Await with Promises" Lesson
[00:00:00]
>> So this is the next thing we need to wrap our heads around before we can ever forget our doggo that we've so desperately want, okay? So yeah, so a weight tells JavaScript, okay, don't be Joey. Don't be just like trying to go wait stop, like the Spice Girl said, and wait for my unsynchronized operation to be done before you go on and continue trying to run my code.
[00:00:27]
So in the case of a promise, what it does is it waits for the promise to be resolved to the value that JavaScript is giving us an IOU for before it goes on and continues running our program. So for example, when we call fetch, we get a promise.
[00:00:50]
And if we await, we put the word await before our call to fetch. We're telling JavaScript, don't just give me back that pending promise like you just did when I put it in with no await. Wait for the promise to be done, and then give me the value of the promise, and in this case fetch returns a response object.
[00:01:14]
So this is going back to kind of like how HTTP requests and responses work which is a little bit out of scope and sort of more general web concept. But suffice it to say that when we try to fetch a URL or when in my browser, I just type in frontendmasters.com.
[00:01:31]
The browser sends a request for that resource at that location, and then it receives, hopefully, a response back with the webpage, or with the hounds in this case. And so let's try now, what happens if we use a weight. So now, if I use a weight, I can then get the value returned or the value that that promise resolves to.
[00:02:00]
In this case the value of the fetch call returns a promise but what I really want is the value that that promise is an IOU for and that's what await is gonna grab for me, and it's going to tell JavaScript stop. Wait for that promise to resolve, and then this whole await fetch is going to evaluate to a response, which I can capture in my variable response here.
[00:02:22]
So let's try it out. Okay, so now, we've actually got something that looks more meaningful. It's still not a list of hound, though, so we'll talk about that in a second. But now, what we've got is a response object. And here, we're starting to see some things that sound very HTTP.
[00:02:44]
For example, we have like a status 200 which I don't know if y'all remember my little friend HTTP Cat 200 means okay. Success, all good. [LAUGH] So there could be other things, like 404 is another one that you might have seen. Not found.
>> [LAUGH]
>> A little treat for the cat people, cuz they've been seriously underserved by my GIFs here.
[00:03:15]
[LAUGH] So, for example, it has a status back, and then it has some other stuff going on. So this is a response object, which is JavaScript's representation of an HTTP response similar to how a HTTP, sorry, an HTML element. Object is its representation of something from the DOM.
[00:03:39]
And what we really care about here is in its body property, the response body, is what we really care about, or as the Spice Girls remind us, slam your body down. The body is what we really want to be working with here, when we're trying to request a resource.
[00:03:57]
But if we look back at our object, okay, we see there's a body property, but it says it's a readable stream. Why don't realize? This is a stream of data that, well, it's apparently readable, so there must be some way to read it. So what we need to do is we need to read the data that's returned that that's part of this response or that it's body.
[00:04:17]
So in other words, we need to slam the body down. [LAUGH] And that's gonna be our next task now responses have a method called JSON. Response.JSON is going to, Read that stream of bytes that is the body data and parse it as a JSON object, which we said is what we expect at the resource at this API endpoint that we're looking for.
[00:04:50]
So it's JSON object, JavaScript object notation object. So this is just a conventional format that JavaScript knows how to read. And the way it knows how to read that is through this dot JSON property that's built into response type objects. So let's try to do this now. Response.JSON, and if you have a really, really good eye, you might be noticing something weird here, but we can talk about in a second.
[00:05:20]
So if I call that response.JSON, gosh, another promise. And so this is an example of what we were just talking about. Another operation that doesn't involve any network activity. It doesn't involve me making a telephone call to the dog API. It does however take some time for JavaScript to go reading through all of those bytes and then making sense of them as a JSON object.
[00:05:44]
So .JSON Then on a response object is also something that gives me an IOU for a value in asynchronous operation, that gives me a promise. But maybe it doesn't take as much time as let's say talking to the network. Question?
>> Should we add a weight in front of response.JSON?
[00:06:04]
>> Well, gee, golly, sounds like somebody's got it. Yeah. So again, a weight is our way of telling JavaScript, hey, stop, wait for my promise to be done and then give me the value of the promise, not just the promise itself. An IOU is useless to me, I can't throw a ball to play fetch with an IOU.
[00:06:25]
[LAUGH] I want the dogs, I want the dogs list I don't want the IOU for the dogs list, so yes we are going to use more awaits here. And it's starting to feel like maybe this is getting frustrating, like we have a lot of stuff to work through here and at a certain point you might want to give up like Gretchen Wieners with trying to make fetch happen.
[00:06:46]
And you might feel like Regina George is saying stop trying to make this happen. I mean, girls, but don't give up. Let's not give up. We have our friend. Wait. So let's try again. So, now what we've got, we're gonna we're gonna have to start over, essentially, but that's okay.
[00:07:02]
[LAUGH] We're going to have to await the fetch. And then, await the response.json in order to actually get our body. Finally, we will slam the body down, so let's try this again. And, I'm just gonna reload here. Okay, so now I'm gonna execute these separately. So, we're doing this the same time, we've got response is a weight fetch.
[00:07:32]
So response is a response object, and then I'm going to call .JSON. Wait that excellent, excellent detective work, folks in the chat. And then I can capture that value as a variable like body. So now, okay, now, body is this object, that is actually what we expected, which is what our browser found, when we went to that URL and actually has our dog data.
[00:08:03]
Finally, that is so fetch. Help you follow folks we're saving grace because anyway I couldn't resist the fetch. So now we have some data. Success, hooray, fulfilled, resolved, finally awaited. But now we have to do something with it. So, [LAUGH] our work has just begun, but we got the data at least, all right?
[00:08:30]
Let me pause here cuz this is a lot of a waiting. [LAUGH] There's one tiny, ginormous can of worms. I want to not open, but let you know is out there as a can of worms in JavaScript. Yes, question.
>> What can we do when our fetch request throws an error?
[00:08:50]
>> JavaScript does also give us tools for being able to look out for the possibility that we might get an error. And any time that we're fetching something from the internet, it's possible that the website is down that dog API has gone offline, or that they changed how their URL system works.
[00:09:10]
And the URL that I thought was gonna work doesn't return what I thought it would anymore, or any number of other things could go wrong. A shark could have chewed through the cables. So we do wanna be aware of the fact that something could go wrong here. And so far we've been writing very optimistic code that assumes that everything's gonna be fine.
[00:09:29]
So a little bit later, we're gonna be talking about how we can handle errors in JavaScript, as it's also called how we can catch errors. So there's a construct called try catch that we're gonna look at a little bit later that is gonna allow us to do this.
[00:09:48]
>> What happens if we just use fetch? Do we just never get an answer?
>> What happens if we just use Fetch, do you mean like for example if we do like let, new response equals fetch,
>> No, no, maybe do the fetch the dog.
>> Yeah, sure right.
[00:10:09]
>> It's running on console, right? And there's a promise pending.
>> Uh-huh. And then what do we do? How do we talk to that promise anymore? How do we,
>> It's just never gonna give us an answer. We just wait forever?
>> Is it just gonna be pending forever?
[00:10:26]
So, what's happening here, is that since we didn't like capture this value at all, we didn't assign it to a variable. We didn't like assign it to a property of an object or something like that, like we don't have any way of pointing at the promise that this fetch evaluated to.
[00:10:48]
So what happens in our dev tools in our console here is that JavaScript evaluated this code, this line fetch. It saw that it evaluated to a promise and at the time that evaluated it, the promise was in state pending, and it gave me that back in the console.
[00:11:07]
>> Now in the background, somewhere that promise has gone ahead, and its lifetime is like lived a million years. And maybe isn't a different state owl, maybe or maybe not, we don't know, but now we don't really have any way to talk to it and ask it hey promise, what's your state now?
[00:11:23]
However, there is a way. So what we've been talking about is await, because wait I think is the easiest way for us to say hey, JavaScript stop, pretend, that this asynchronous operation, that you're gonna go and do some time later. Pretend that it's synchronous, and that we actually have to wait for it to be done before we keep going on with our code.
[00:11:45]
There is another way that we can tell JavaScript, hey JavaScript when this promise is done, when it has fulfilled or rejected, do something with it, and that is the then method on a promise. So we're not really gonna practice, like working with this, because await I think makes it easier to do a similar thing.
[00:12:11]
So then was the earlier way of dealing with promises where what happens is So we say, promise.then, and we give it a callback. And usually, the way the callback works is it takes in whatever the value that the promise resolved to. And sorry, I'm saying callback because we're writing a small anonymous function that's gonna execute some time later.
[00:12:37]
We're telling JavaScript take this function and call it back to me whenever this thing happens, same as we did with our event handlers, where we also passed in a callback function. So we'll say like something like console.log value, for example. Now what should happen let's find out is that JavaScript is gonna wait until it sees that this promise has resolved or fulfilled.
[00:13:07]
And then, it's gonna take whatever value it fulfilled to pass it in to the little anonymous function I've declared here with my arrow, and then do whatever I set to do, which in this case was log the value. So let's try. So now, if we see this whole thing resolved to a promise, and at the time that it evaluated in the console, it was pending.
[00:13:30]
But then a few instants later JavaScript, got the resolution got the fulfilled value, and then called my callback which console logged the response. So, there is another way to work with these promises. Which is the then method. But if you're like me, it's maybe becomes a little bit tricky to think about like, okay, give me a function that I'm gonna wait free.
[00:14:03]
I'm gonna give you a function you're gonna wait to call it until you're done with the promise. Whereas if we use a weight, we can just sort of pretend like that promise is just a regular function call that's gonna produce a value, if that makes sense. Sorry, I should say, we can pretend that the asynchronous operation like fetch, which returns a promise, is just a regular function call that returns a value instead of an asynchronous.
[00:14:28]
I owe you of a value. So, these are both options, and you can read all about promises, and then in our BFF MDM.
>> Could I write await in front of any function, I want for to wait?
>> Can you like, wait for, for example?
>> Yes, you can't.
[00:14:48]
>> You sure can?
>> Okay.
>> But, as we're gonna see in a second, you can't write await just anywhere. I can write it in the console. I can write it in a few other places, but I can't just throw away it around, but we're gonna talk about that in a second.
Learn Straight from the Experts Who Shape the Modern Web
- In-depth Courses
- Industry Leading Experts
- Learning Paths
- Live Interactive Workshops