DEV Community

Lokesh
Lokesh

Posted on

JavaScript Promises

A Promise in JavaScript is used to handle operations that take time to complete, such as fetching data from an API.

Let's understand Promises with simple examples!

1. What Is a Promise?

A Promise represents the result of an operation that may be available now or in the future.

A Promise has three states:

  • Pending: Waiting for the result.
  • Fulfilled: The operation completed successfully.
  • Rejected: The operation failed.

For example, when you order food online, your order is pending while being prepared, fulfilled when delivered, or rejected if it fails.

2. Creating a Promise

We can create a Promise using new Promise().

const myPromise = new Promise((resolve, reject) => {
    let success = true;

    if (success) {
        resolve("Task completed successfully!");
    } else {
        reject("Task failed!");
    }
});
Enter fullscreen mode Exit fullscreen mode

Here:

  • resolve() is called when the operation succeeds.
  • reject() is called when the operation fails.

3. Using .then()

We use .then() to handle a successful result.

myPromise.then((result) => {
    console.log(result);
});
Enter fullscreen mode Exit fullscreen mode

Output:

Task completed successfully!
Enter fullscreen mode Exit fullscreen mode

The value passed to resolve() is received by the callback inside .then().

4. Using .catch()

We use .catch() to handle a rejected Promise.

const myPromise = new Promise((resolve, reject) => {
    reject("Something went wrong!");
});

myPromise
    .then((result) => {
        console.log(result);
    })
    .catch((error) => {
        console.log(error);
    });
Enter fullscreen mode Exit fullscreen mode

Output:

Something went wrong!
Enter fullscreen mode Exit fullscreen mode

This helps us handle errors without leaving them unhandled.

5. Promise with setTimeout()

Let's create a Promise that completes after two seconds.

const myPromise = new Promise((resolve) => {
    setTimeout(() => {
        resolve("Data received!");
    }, 2000);
});

myPromise.then((result) => {
    console.log(result);
});
Enter fullscreen mode Exit fullscreen mode

After approximately two seconds, the output is:

Data received!
Enter fullscreen mode Exit fullscreen mode

The Promise remains pending until resolve() is called.

6. Using Promises with Fetch API

Promises are commonly used to get data from APIs.

fetch("https://fakestoreapi.com/products")
    .then((response) => response.json())
    .then((data) => {
        console.log(data);
    })
    .catch((error) => {
        console.log("Error:", error);
    });
Enter fullscreen mode Exit fullscreen mode

Here:

  • fetch() sends a request to the API.
  • The first .then() converts the response body into JSON.
  • The second .then() receives the product data.
  • .catch() handles errors such as network failures.

Note that fetch() does not automatically reject for HTTP errors like 404. In real projects, you should also check response.ok.

Conclusion

Promises make asynchronous operations easier to manage in JavaScript.

Remember these important points:

  • resolve() represents successful completion.
  • reject() represents failure.
  • .then() handles successful results.
  • .catch() handles errors.
  • Promises are widely used with APIs and async/await.

Top comments (0)