JavaScript Promises

JavaScript Promises

Let's understand Promises in JavaScript

·

4 min read

What is meant by a promise in general, is to say definitely that you will do or not do something or that something will happen

In general, a declaration that one will do or refrain from doing something specified. Ex: Your dad said, "I will buy you a new dress".

You don't know when your dad will buy you a new dress—tomorrow, next week, or next month. He just promised you, right?

That is a promise. A promise has three states. They are:

  1. Pending

  2. Fulfilled

  3. Rejected

Case 1(Pending): You don't know when you will get the dress or how long it takes.
Case 2(Fulfilled): Your dad bought you a new dress.🎉 🥳.
Case 3(Rejected): Your dad forgot to get you a new dress.😢

Promises begin the pending, or incomplete, stage. If the process is successful or completed, it reaches a fulfilled state; if there is any error in the process, the process is rejected.

How to create a promise

let promise = new Promise(function(resolve, reject){
   // code goes here
});

The Promise() function accepts two functions resolve() and reject(). If the promise returns successfully, the resolve() the function is called. And, if an error occurs, the reject() the function is called.

const dadwillbuydress = true; 
let dress = new Promise(function (resolve, reject) {
    if (dadwillbuydress) {
        resolve("Dad bought you a new dress");
    } else {
        reject("Dad did not get the new dress");
    }
});
console.log(dress); // Dad bought you a new dress

If the variable is true (dadwillbuydress=true;) then, the condition will resolve otherwise the promise function will reject.

In the above example, the promise function is true so it returns "Dad bought you a new dress" if the variable is false (dadwillbuydress=false;) then, the condition will reject. and returns "Dad did not get the new dress".

Chaining promises in JavaScript

Chaining breaks a task down into small steps and then teaches each step within the sequence by itself.

Promises are chainable. Let's say you promised your friend I will wear the new dress on my birthday when dad brought me. It becomes the chain system

The first dad promised you : "I will buy you a new dress".
second You promised your friend: "I will wear the new dress on my birthday".

And these chains go on, The promises chaining continues based on the condition (resolve, reject).

The promise is resolved using methods then(), catch() and finally().

.then() return the resolved state, .catch() return reject state.
.finally() executed when state is completely resolved or rejected.

JavaScript then() method

The JavaScript then() method used with the callback when the promise is successfully fulfilled or resolved.

The .then() in javascript takes two parameters, the callback function for the success and the callback function for failure cases of the Promise.

// returns a promise
let countValue = new Promise(function (resolve, reject) {
  resolve("Promise resolved");
});
// executes when promise is resolved successfully
countValue
  .then(function successValue(result) {
    console.log(result);
  });

The then() method is called when the promise is resolved successfully. You can chain multiple then() methods with the promise.

JavaScript catch() method

The catch() method is used with the callback when the promise is rejected or if an error occurs.

// returns a promise
let countValue = new Promise(function (resolve, reject) {
   reject('Promise rejected'); 
});
// executes when promise is resolved successfully
countValue.then(
    function successValue(result) {
        console.log(result);
    },
 )
// executes if there is an error
.catch(
    function errorValue(result) {
        console.log(result);
    }
);

The promise is rejected. And the catch() method is used with a promise to handle the error.

JavaScript finally() method

The finally() method gets executed when the promise is either resolved successfully or rejected.

// returns a promise
let countValue = new Promise(function (resolve, reject) {
    // could be resolved or rejected   
    resolve('Promise resolved'); 
});
// add other blocks of code
countValue.finally(
    function greet() {
        console.log('This code is executed.');
    }
)

Conclusion

Promises are one of the important concepts in Javascript it helps us understand more about functions and used in projects to shorten the code instead of writing large code blocks.
Thank you🌷 .
Comment for any queries.