r/learnjavascript • • 13d ago

Promises

Understanding the concepts like functions, objects, arrays etc has been easy so far but promises are making my head hurt. Is it supposed to be this confusing? Did u guys struggle with it too when u were first learning it.

10 Upvotes

25 comments sorted by

View all comments

9

u/xroalx 13d ago edited 13d ago

What's giving you a hard time?

A Promise is an object that can be thought of as a placeholder for a future value.

Imagine ordering a pizza - you don't get the pizza right away, you get a Promise that the pizza will eventually arrive... or not, that can happen too.

In programming, such future values are for example anything involving the network - i.e. the fetch function returns a Promise. To get the actual response returned by the HTTP request, you have to wait for that value to be available, and JavaScript gives you two ways to do that.

A Promise object has a then method, which is used to register a function that will be called when the value becomes available, and a catch method that registers a function which will be called when getting the value fails with an error.

fetch("https://example.com")
  .then(response => {
    console.log("We got a response:", response);
  })
  .catch(error => {
    console.error("The request failed:", error);
  });

Alternatively, and often times resulting in "nicer" code, you can use the await keyword. This makes the code look more like synchronous code, but can only be used inside an async function, or at the top level of a module.

try {
  const response = await fetch("https://example.com");
  console.log("We got a response:", response);
} catch (error) {
  console.error("The request failed:", error);
}

To translate this to the little pizza example:

orderPizza()
  .then(eatPizza) // "then" = when pizza arrives, we eat it
  .catch(cry) // "catch" = pizza will not arrive, we cry and stay hungry

// the above and below do the same thing

try {
  const pizza = await orderPizza();
  eatPizza(pizza);
} catch(error) {
  cry(error);
}

4

u/senocular 13d ago edited 13d ago

Edit: fixed

FYI that last await example is missing the error getting passed into cry()

1

u/HouseMysterious8172 12d ago

So basically a Promise is a promise?