Day 13: Async
Lesson 2: Promise Chaining
In the last lesson we have have a call to the PokeAPI using the
fetch function made available to us by the browser.
But we haven't yet accessed the data that comes back from the PokeAPI.
To do that we need to use another promise, which allows me talk about how you can control your flow in asynchronous code.
One of the hardest things with async code is understanding when things happen and how you get access to the data when those things complete. In the last lesson we looked at
What we didn't talk about is that you can chain multiple
.then()s together if you need to things one after the other that are asynchronous - and it turns out that we want to do just that!
Here's a reminder of the code we have:
1const pokeApi = 'https://pokeapi.co/api/v2/pokemon/ditto';\n 2fetch(pokeApi).then( 3 (res) => console.log("Done!") 4);
The data we want from the PokeAPI is stored within the
res object we have in that first function. Sadly we can't just access it like this though:
res.data. We need to be more explicit than that.
fetch() will let us access that data, via another promise. Don't panic though, because the ability to chain multiple
.then()s together makes this easy. Let's take a look:
1const pokeApi = 'https://pokeapi.co/api/v2/pokemon/ditto';\n 2fetch(pokeApi).then( 3 (res) => res.json() 4).then( 5 (data) => console.log(data) 6)
You will see in the first
.then() function that we are no longer logging anything, we are instead calling
.json() on the
res object. This is a function that asynchronously gets the data that was sent to us in the response and turns it into a JSON object.
How do we know it returns a promise? Sadly there's no obvious way to know other than checking the documentation or learning about it via a tutorial like this. Either way, it returns a promise, just like the main
.fetch() function does.
One difference is though that since we are inside a
.then() when calling that promise we can simply return it and then add a new
.then() on to access the result of the
.json() promise. This means we don't start to get horribly nested code, can you imagine the mess of brackets and braces if we had to do .json().then( data .... )`? Eew!
This means we can keep our code nice and flat and have a
(data) => console.log(data) function passed into our final
.then() to access the data 😀
There's no limit to how many
.then()s you can chain together this this, the only caveat being that each one need to return a promise so that the next
.then() has a promise to work on.
res.json() returns a promise, but there's no network request like there is with
fetch() and it's relevant functions meaning that accessing the data in
res.json() is done with a promise. The reason for this is due to the way the data base been received and temporarily stored, it does make sense, it's just beyond the scope of a course like this.