DEV Community

Cover image for Understanding Fetch API and Promises in JavaScript.
Megalraja
Megalraja

Posted on

Understanding Fetch API and Promises in JavaScript.

Fetch API & Promises — Imagine Ordering Food

Learning fetch() and Promises can feel confusing at first.

So let's forget code for a minute and imagine you're ordering pizza.

You place an order:

fetch("pizza-api.com/order");
Enter fullscreen mode Exit fullscreen mode

You don't get the pizza immediately.

The restaurant says:

"Don't worry, your order is being prepared. I'll let you know when it's ready."

That's basically a Promise.

Promise

A Promise represents something that will have a result in the future.

It can be:

Pending     → Pizza is being prepared
Fulfilled  → Pizza is ready
Rejected   → Sorry, we're out of pizza
Enter fullscreen mode Exit fullscreen mode

.then()

When the pizza arrives, you can do something with it:

fetch("pizza-api.com/order")
    .then(response => response.json())
    .then(data => {
        console.log("Pizza arrived!", data);
    });
Enter fullscreen mode Exit fullscreen mode

Think of .then() as:

"When you get the result, do this."

.catch()

But what if the restaurant says:

"Sorry, something went wrong with your order."

That's where .catch() comes in:

fetch("pizza-api.com/order")
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.log("Order failed!", error));
Enter fullscreen mode Exit fullscreen mode

So what's actually happening?

You
 ↓
fetch() 
 ↓
Promise 
 ↓
.then() → "Pizza arrived!" 
 ↓
.catch() → "Something went wrong!" 
Enter fullscreen mode Exit fullscreen mode

And there's one more interesting thing:

response.json()
Enter fullscreen mode Exit fullscreen mode

also returns a Promise.

Promise → "Wait, I'll get back to you."

That's why we use another .then() after it.

The easiest way I remember it:

fetch() → Place the order
.then() → "Great! Here's what to do with the result."

.catch() → "Oops, something went wrong."

Once I started thinking about Promises this way, fetch() and asynchronous JavaScript became much less confusing.

Sometimes the best way to learn programming isn't more code — it's finding the right analogy.

Top comments (0)