DEV Community

Cover image for Promise in JS
Rakshambika
Rakshambika

Posted on

Promise in JS

What is promise?

  • A Promise is an object used to handle the result of an asynchronous operation.

Example:

let promise = new Promise((resolve, reject) => {

    let success = true;

    if (success) {
        resolve("Data received successfully");
    } else {
        reject("Failed to receive data");
    }

});
Enter fullscreen mode Exit fullscreen mode

States in Promise:

A Promise has 3 states:

  1. Pending → Operation is still running
  2. Fulfilled → Operation completed successfully
  3. Rejected → Operation failed


Why do we need Promises?

Before Promises, asynchronous operations were commonly handled using callbacks.

example:

getUser(function(user) {

    getOrders(user, function(orders) {

        getPayment(orders, function(payment) {

            console.log(payment);

        });

    });

});
Enter fullscreen mode Exit fullscreen mode

When many asynchronous operations depend on each other, callbacks can become deeply nested.

This is called Callback Hell.

Promises make the code easier to organize:

getUser()
    .then(user => getOrders(user))
    .then(orders => getPayment(orders))
    .then(payment => console.log(payment))
    .catch(error => console.log(error));
Enter fullscreen mode Exit fullscreen mode

So, one major reason we need Promises is:

Promises make asynchronous code easier to read, manage, and handle errors .


Uses of Promises:

  1. Handling asynchronous operations
  2. Handling success and failure
  3. Promise chaining
  4. Avoiding Callback Hell
  5. Working with multiple asynchronous operations

Promise to handle success:

When the operation is successful, call resolve().

const promise = new Promise((resolve, reject) => {

    let success = true;

    if (success) {
        resolve("Data received successfully");
    }
});
Enter fullscreen mode Exit fullscreen mode

Then we handle the successful result using .then():

promise.then(result => {
    console.log(result);
});
Enter fullscreen mode Exit fullscreen mode
Promise
   ↓
resolve()
   ↓
FULFILLED
   ↓
.then()
   ↓
Success result
Enter fullscreen mode Exit fullscreen mode

Promise to handle error:

When the operation fails, call reject().

const promise = new Promise((resolve, reject) => {

    let success = false;

    if (success) {
        resolve("Data received");
    } else {
        reject("Failed to get data");
    }
});

Enter fullscreen mode Exit fullscreen mode

Then handle the error using .catch():

promise.catch(error => {
    console.log(error);
});

Enter fullscreen mode Exit fullscreen mode
Promise
   ↓
reject()
   ↓
REJECTED
   ↓
.catch()
   ↓
Error
Enter fullscreen mode Exit fullscreen mode

Handling both success and error:

Usually, we handle both together:

const promise = new Promise((resolve, reject) => {

    let success = true;

    if (success) {
        resolve("Data loaded successfully");
    } else {
        reject("Something went wrong");
    }
});

promise
    .then(result => {
        console.log("Success:", result);
    })
    .catch(error => {
        console.log("Error:", error);
    });

Enter fullscreen mode Exit fullscreen mode

Top comments (0)