Web Technologies

Basics of promise in fetch api to make ajax call – Tutorial 8

Let’s get rid of XMLHttpRequest and its methods like open, send, etc. We now use fetch API to make ajax calls.

Fetch uses Promises

This means data from a fetch request is therefore given back to us, via a promise

You can’t get the value from a promise directly  

DON’T PANIC. To get the value from a promise, all you need to do is register a .then() statement. This is a callback function that JavaScript will execute when the Promise has either been successful or failed

The .then() statement takes 2 optional parameters – the onFullfilled() method and the onRejected() method

Market convention is to use only the onFullfilled() method, and to catch all other errors in a universal .catch() block

Fetch API and Promises (Explained Simply)

Imagine you’re ordering a pizza. You ask the pizza shop for a pizza (that’s like making a request), and then you wait for them to send it to you. You don’t know exactly when the pizza will arrive, but you wait for it. When the pizza finally arrives, you get what you wanted!

In programming, when we ask for something from the internet, like data from a website, we can use the fetch() function. It’s like ordering something from the internet.

Now, here’s the cool part: fetch gives us a Promise. Think of a Promise as a promise from the pizza shop that they will either give you the pizza (if everything goes well) or tell you if something went wrong (like if they ran out of pizza).

You can’t just take the pizza (data) immediately after ordering. You have to wait for the promise to be fulfilled. But how do you know when it’s ready?

How to Get the Pizza (Data) When It’s Ready:

You need to use something called a .then(). This is like telling the pizza shop, “When you’re done, let me know and I’ll come get the pizza!”

  • .then() is where you say, “When the pizza is ready, I’ll take it!” In programming, this is called a callback.

There are two ways the pizza shop can respond:

  1. If the pizza is ready (Promise is fulfilled) – This is like saying, “Yay! My order is complete!” (We handle this part with the onFulfilled() method).
  2. If there was an issue (Promise is rejected) – Maybe they didn’t have enough cheese, so they can’t fulfill your order. This is where we use onRejected() to handle errors.

Catching Errors

Sometimes things go wrong – maybe the pizza shop runs out of ingredients or the delivery guy gets lost. In programming, if something goes wrong, we use .catch() to catch the mistake and handle it. It’s like saying, “If there’s a problem with the pizza, let me know, and I’ll fix it.”

Summary:

  • fetch() is like ordering a pizza.
  • Promise is the pizza shop’s promise to either give you your pizza or tell you something went wrong.
  • .then() is how you wait for the pizza and then take it when it’s ready.
  • .catch() is how you handle any problems with the pizza.

Next lession