Nic
This week I learnt...

This week I learnt...

Asynchronous JavaScript

Until recently, I thought asynchronous JavaScript was so complicated. It's not helped by the multitude (or so it seems) or ways to handle it. The simplest way I've found is to use async await and fetch. Because they all do what they say the do.

You can think of fetch like playing fetch with a dog. First you throw the ball:

const playBall = fetch(ball);

And then you need to wait for the dog to return with the ball:

const playBall = await fetch(ball);

Then the dog returns with the ball:

const playBall = await fetch(ball);
return ball;

All of that can only happen within an asynchronous function. An asynchronous function is easy to make: you just put async at the start of the function.

async function playWithDog() {
  const playBall = await fetch(ball);
  return ball;
}

That's it: it really is that simple.

A good API to try this with is TheDogAPI or TheCatAPI if that's your preference. Neither of them need an API key and they will give you dog/cat photos. Here's a real world example using the code from above.

async function getDog() {
  const request = await fetch(https://api.thedogapi.com/v1/images/search)
  const data = request.json();
  return data;
}

If you paste api.thedogapi.com/v1/images/search into your browser you'll see the JSON data it gives you. And you can click on the url to see a random dog picture.

 
Share this