DEV Community

Ragul
Ragul

Posted on

Promises in JavaScript

Imagine you order food at a restaurant. The waiter doesn't hand you the food right away — they hand you an order ticket instead. That ticket is a promise: your food will arrive, or the kitchen will tell you they're out of what you ordered. Either way, you're not just standing there frozen, waiting. You can keep chatting with your friends until the food (or the bad news) shows up.

That's exactly what a Promise is in JavaScript. It's a placeholder for something that will finish later, like fetching data from the internet, which doesn't happen instantly.

The Three States

A Promise is always in one of three states:

  • Pending – still waiting, like your food order still cooking
  • Fulfilled – it worked, your food arrived
  • Rejected – it failed, the kitchen ran out

Once it lands on fulfilled or rejected, it stays there. No take-backs.

Why Not Just Wait?

JavaScript doesn't like to sit around doing nothing while waiting for slow things like network requests. Instead of freezing the whole page, it hands you a Promise and moves on. Later, when the slow thing finishes, your Promise tells you what happened.

Using a Promise

The most common way to work with Promises today is async/await, because it reads almost like normal step-by-step code:

async function getWeather() {
  const data = await fetchWeather();
  console.log(data);
}
Enter fullscreen mode Exit fullscreen mode

The await just means "pause here until this is done, then continue." If something goes wrong, you catch it like this:

async function getWeather() {
  try {
    const data = await fetchWeather();
    console.log(data);
  } catch (error) {
    console.log("Couldn't get the weather.");
  }
}
Enter fullscreen mode Exit fullscreen mode

That's really the whole idea: await for waiting, try/catch for handling problems.

Top comments (0)