DEV Community

Cover image for What are JavaScript Promises Anyway?
Mark Harless
Mark Harless

Posted on

4

What are JavaScript Promises Anyway?

A promise in JavaScript is much like a promise in real life. It's quite a fitting name and I applaud the person who thought of it. In code, you use it to do something, typically asynchronously. When the promise is complete, either one of two things happen: you fulfill the promise or you fail to fulfill the promise.

A Promise is a constructor function, so you must use new to create one. Here's what it looks like:

const pinkyPromise = new Promise((resolve, reject) => {
  // your code here
});
Enter fullscreen mode Exit fullscreen mode

You'll notice a Promise takes in a function as an argument with two parameters: resolve and reject. Obviously, you can name these parameters whatever you want. I typically use res and rej because it's easier to type.

A promise has three states: pending, fulfilled and rejected. The promise I showed you above will always be in the pending state because we didn't tell the function how to fulfill the promise.

Here's how we can fulfill a promise:

const pinkyPromise = new Promise((res, rej) => {
  if() {
    resolve("Promise was fulfilled");
  } else {
    reject("Promise was rejected");
  }
});
Enter fullscreen mode Exit fullscreen mode

We added a simple if statement that tells the promise what it should do if it's resolved or rejected. We use strings here but you can pass anything as the argument.

A typical use case scenario for promises is to fetch data from an external API or any sort of asynchronous function that takes an unknown amount of time to complete. Let's say we want to get weather data from an API. What do we do after it has successfully fulfilled its promise? That is where the then method comes in:

const pinkyPromise = new Promise((res, rej) => {
  if() {
    resolve("Promise was fulfilled");
  } else {
    reject("Promise was rejected");
  }
})
.then(result => {
  console.log(result)
});
Enter fullscreen mode Exit fullscreen mode

In the above example, we are telling the promise pinkyPromise to log the results to our terminal so we can read it, like weather data. The then method will only run when the promise has been resolved. The catch method is used in very much the same way as then except it only runs if it was rejected:

const pinkyPromise = new Promise((res, rej) => {
  if() {
    resolve("Promise was fulfilled");
  } else {
    reject("Promise was rejected");
  }
})
.then(result => {
  console.log(result)
})
.catch(error => {
  console.log(error)
})
Enter fullscreen mode Exit fullscreen mode

You can see that, again, we are just logging what we receive back into the console but this time it's the error. Keep in mind result and error can be named whatever you want it to be and the then and catch methods can be on the same line as the closing parenthesis. I only put it on a new line to better see what we added to our promise.

And that's it! To recap, a JavaScript promise is usually used for an asynchronous task that takes an unknown amount of time to complete, like fetching for data. The promise is either resolved or rejected. If it's resolved, then the then method will run. If it's rejected, then the catch method will run.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay