JavaScript Promises
Tags: javascript, programming, beginners, tutorial
Published: 2023-10-18 17:07:52

Imagine that you’re a top singer, and fans ask day and night for your upcoming song.

To get some relief, you promise to send it to them when it’s published. You give your fans a list. They can fill in their email addresses so that when the song becomes available, all subscribed parties instantly receive it. And even if something goes very wrong, say, a fire in the studio, so that you can’t publish the song, they will still be notified.

Everyone is happy: you, because the people don’t crowd you anymore, and fans, because they won’t miss the song.

This is a real-life analogy for things we often have in programming.

Now, just like our singer's promise to deliver that eagerly awaited song, JavaScript also offers a powerful tool to handle similar situations in programming. Enter Promises.

## What are Promises in JavaScript?

In the realm of programming, a "Promise" is like a contract. It's an object representing the eventual outcome of an asynchronous operation. This could be something like fetching data from a server, reading a file, or any task that takes a significant amount of time.

**The Three States of a Promise**

Promises in JavaScript have three possible states:

1. **Pending:** This is the initial state. The operation hasn't been completed yet.

2. **Fulfilled:** The operation was successful, and the Promise now has a result.

3. **Rejected:** Something went wrong, and the operation couldn't be completed. The Promise has an error.

Just like our singer's promise to deliver the song, JavaScript Promises uphold their commitment, ensuring that you'll eventually get a result, even if there are unexpected hurdles along the way.
 
Now, let's dive into the practical aspect of working with Promises in JavaScript.

## Creating a Promise

A Promise in JavaScript is created using the new Promise() syntax. Here's an example:

```
const myPromise = new Promise((resolve, reject) => {
  // Simulating an asynchronous task
  setTimeout(() => {
    const success = true;
    if (success) {
      resolve('Task completed successfully'); // Resolve the Promise
    } else {
      reject('Task failed'); // Reject the Promise
    }
  }, 2000); // Simulating a 2-second delay
});

```
In this example, we've created a Promise named myPromise. It's constructed with a callback function that takes two parameters:** resolve** and **reject**. These are functions provided by JavaScript to handle the eventual completion or failure of the asynchronous operation.

If the operation is successful, we call** resolve** with the **result**. If there's an error, we call **reject**.

**Handling Promise States**
Using .then() and .catch()

To manage the outcomes of a Promise, we use the **.then() **and **.catch()** methods.

```
myPromise
  .then((result) => {
    console.log(result); // Handle the resolved state
  })
  .catch((error) => {
    console.error(error); // Handle the rejected state
  });

```
Here, if the Promise resolves, the first function inside **.then()** executes. If it rejects, the function inside **.catch()** handles the error.

**Returning Values from Promises**

You can return values from a resolved Promise using **return.**

```
const myPromise = new Promise((resolve) => {
  setTimeout(() => {
    resolve('Returned value');
  }, 2000);
});

myPromise
  .then((result) => {
    console.log(result); // Output: Returned value
  })
  .catch((error) => {
    console.error(error);
  });

```
In this example, the resolved Promise returns the value **'Returned value'**.

In summary, Promises are a fundamental feature in modern JavaScript development, providing an organized and efficient way to handle asynchronous tasks. They allow for smoother execution of code, ensuring that results are managed appropriately, even in the face of unexpected challenges.

**Subscribe to our Newsletter**

Stay up-to-date with the latest in JavaScript development! Subscribe to our daily newsletter for insightful articles, tutorials, and news delivered straight to your inbox.

[Subscrible](https://uccodejavascript.ck.page/e27a96062c)