30 Days Of JavaScript

Day 13: Async

Lesson 1: Promises

In JavaScript we have something called a Promise. It's a special type of function that JavaScript can execute later, when it's ready to, rather than right away when it first sees it. Here's an example:

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.

But it's reasonably complicated and, to be honest, not all that useful. I can count on two hands how many times I've had to work with Promises to that level in the last 15 years of working with JavaScript.

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

We pass pokeApi into 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 fetch() uses Promises to return data later, when it's ready, without blocking the main thread of your JavaScript code. So, things can appear "out of order" to us, those console log messages are showing in the order that they happen, and thanks to Promises that will very likely be different to how we wrote the code.

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 fetch() called.

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!

Outline

Go Pro?

If you upgraded to pro, sign in here

  • About
  • Blog
  • Privacy
Looking to email me? You can get me on my first name at allthecode.co