Promise in Javascript

Promise is an object representing the eventual completion or failure of an asynchronous operation.

·

2 min read

Promise in Javascript

A promise is an object. It works as a placeholder for a certain period until we receive a value from an asynchronous operation.

Promise in Javascript is similar to promise in real life. If we do promise to do something, there will be two results of promises. Either the promise is fulfilled or that promise is failed.

let p = new Promise((resolve, reject)=> {
    let a = 1 + 3;
    if(a == 2){
        resolve("resolved")
    }else{
        reject("rejected")
    }
})

p.then((m)=>{
    console.log("promise " + m)
}).catch((e)=>{
    console.log("promise " + e) // promise rejected
}).finally(()=>{
    console.log("Finally entered") // Finally entered
})

A promise is a constructor that takes one function. This function takes two parameters, resolve and reject. The resolve function will be called when there is a promise which is fulfilled and the reject will be called when a promise is failed.

We handle the Promises with then(), catch() and finally(). then() function should be called when you want to get the outcome from the promise.

promise.then(
  (result) => { 
      console.log(result);
  }
);

catch() function will be called to catch any rejected error if there is any.

let promise = getPromise(API);

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

getData();

finally() will be called even if there is a reject call or a resolve call. If the promise resolves, the .then() method will be called. If the promise rejects with an error, the .catch() method will be called. The .finally() will be called irrespective of the resolve or reject.

p.then((m)=>{
    console.log("promise " + m)
}).catch((e)=>{
    console.log("promise " + e)
}).finally(()=>{
    console.log("Finally entered") // always runs
})

A promise object has the following internal properties:

  1. state – This property can have the following values:
  • pending: Initially when the executor function starts the execution.

  • fulfilled: When the promise is resolved.

  • rejected: When the promise is rejected.

2. result – This property can have the following values:

  • undefined: Initially when the state value is pending.

  • value: When resolve(value) is called.

  • error: When reject(error) is called.