What is Promise in Javascricpt

This blog is related to promises in javaScript and methods of Promises.

Need of Promise?

  • To run code in an asynchronous way

  • Avoid the callback hell issue.

  • During API response getting time.

What is a Promise?

promise.avif

It represents the completion of an asynchronous operation and its resulting value. So that asynchronous operation return promise which will have value available in future.

A promise has three states

  1. Pending - Initial state, when Promise is neither fulfilled nor rejected

  2. Fulfilled/ resolve - When the resolve() method is executed, indicating that the operation was completed successfully

  3. Rejected -: When the reject() method is executed, indicating that the operation failed

How does Promise work? When the first Promise is called, it is a pending state. For example, when we fetch data from API, that returns a promise. So while before getting data, it is pending. It will be in pending until it gets resolved. Once the Promise is resolved, it will be in the Fulfilled state, and if it gets rejected, then the Promise will be in the rejected state.

Promise syntax

- It has been divided into two-part Producing code and consuming code

Producing Code

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

  if (true) {
    resolve('sucessfully resolve')
  }
})

A promise object is created using a new keyword. The Promise object has one callback function, which has two functions as argument (resolve and reject ) If the resolve function runs, it means the Promise fulfilled If the reject function runs, it means Promise rejected.

Consuming code

promise.then(res => console.log(res))
  .catch(err => console.log(err))
  .finally(() => console.log('i will run no mater what '))

.then: always returns a new promise, runs when the promise gets resolved, and we can use the promise to get a resolved result.

.catch: For error handling, we use. If the process gets rejected then the .catch() method will catch errors that occurred in promise.

.finally: either promise gets fulfilled or rejected it does not matter , the code inside this block will run always

Methods of Promise

Promise.all()

when all promise get resolved, then return all results even one promise fail it return all promise failed.

  • Promise. all() method accepts an array of Promises and returns a Promise.

  • If any of the promises is rejected, it immediately rejects with that error.

  • The order of elements in the result array will be the same as the input Promise iterable

//Example 1 
let data = Promise.all([
  new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('2 second  ')
    }, 2000)
  }),
  new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('1 second  ')
    }, 1000)
  }),
  new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('4 second  ')
    }, 4000)
  })
])

data.then(res => {
  console.log('then ', res)
})

Application of Promise.all()

Can be used where we have to download several URLs in parallel and process the content once they are all done. this method is preferred in case of dependant asynchronous tasks.

Promise.allSettled()

  • It returns a promise after all of the given promises have either been fulfilled or rejected, in an array of objects
  • The order of objects in the result array will be same as the input Promise iterable.
  • The resulting array has:

  • {status : 'fulfilled', value : result} for successful response,

  • {status : 'rejected', reason : error} for failed response.
//Example

const promise = Promise.allSettled([
  new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('1 sec')
    }, 1000)
  }),
  new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('3 sec')
    }, 3000)
  }),
  new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('5 sec')
    }, 5000)
  })
])
promise.then(res => {
  console.log(res)
})

Application of Promise.allSettled()

If there is no data dependency on our app then we can ignore the promise that has got reject and we display the success promise output

3.Promise.race()

  • It returns only the response of the promise that resolved fastest

  • If we hit three promises, the promise that results get resolved or rejected first returns. The promised return that response.

  • If the promise that resolve first run rejected function then the race throw an error

// 
const promise = Promise.race([
  new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('3 sec')
    }, 3000)
  }),
  new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('1 sec')
    }, 1000)
  }),

  new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('5 sec')
    }, 5000)
  })
])
// ***
promise.then(res => {
  console.log(res)
})

4. Promise.any()

  • It is similar to Promise. race() but ignore the Promise that gets rejected it returns the promise that gets resolved the fastest
//  ignore the reject promise
const promise = Promise.any([
  new Promise((resolve, reject) => {
    reject('3 sec')
  }),
  new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('1 sec')
    }, 1000)
  }),

  new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('5 sec')
    }, 5000)
  })
])
// ***
promise.then(res => {
  console.log(res)
})

Application : To serve the data to the user from the nearest server as per his location

Summary of Promise methods

Promise all() : An array of resolved values rejects if anyone fails

Promise.allSettled() : return array of objects with status and value for resolved and rejected cases, respectively.

Promise.race() :value of first settled Promise, if error return error

Promise.any() Value of first fulfilled Promise throws Aggregate Error if all are rejected.