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");

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

.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);
    });

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));

So what's actually happening?

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

And there's one more interesting thing:

response.json()

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.

添加评论
点赞收藏
点踩分享查看原文
评论
?
参与讨论