Day 13: Async
Lesson 1: Promises
Promises are a way to say "Go do this, and when it's done come back and let me know so we can do the next thing".
Now I could go into lots of detail about how promises are created and how they are resolved or rejected depending on the result of the "Go do this" part of the sentence above.
However, working with the result of Promises is a daily occurrence - and that aspect is pretty simple to get your head around.
The code below shows how we use promises most of the time as web developers - fetching data from another web service. In this can we are fetching data from the Pokemon API.
Let's break to code down:
fetch is function provided by the browser to let us request data from other places on the internet
pokeApi is the URL for the Pokemon API
fetch() to get the data
There will be a delay between sending that request and getting the response back. To see this add
console.log("Time 1"); to the very top of the playground, and
console.log("Time 2"); to the very bottom. Notice how
res is printed after both of those messages?
But why 🤷♂️?
Well it's because
But that's ok! Because the
.then() allows us to execute the code we want, after
fetch() has done it's job.
Let's break that
.then() down shall we?
.then() wants a function to execute when it's ready that takes (in this case) a single argument - the response from the URL that
So this code:
1fetch(someUrl).then((res) => console.log("Done!"));
Can be read at "fetch something from the URL someUrl, then take the response and pass it into the function
(res) => console.log("Done!")"
You may wonder why I've logged the word Done and not the data in the response,
res? Well, that's because in this case
res is a massive object full of masses of data you don't need to worry about. Getting at the data you care about actually opens the door to the next thing we need to talk about.
On to the next lesson!