Promises in JavaScript

Promises in JavaScript

A promise is a object that would be returning some value in the near future. because of the "in future thing" , promises are well suited for asynchronous operations.

The concept of promises can be explained through an example more clearly. Imagine you are prepping up for a birthday party. your friend promised to buy a party popper , so ram has promised that he would be getting a party popper that's a promise.

// ram buys a party popper
const popperPromise = ramBuysPopper('party popper')

If ram buys a party popper so the promise is resolved. So in JavaScript if the promise is resolved we do the next thing by using .then

 ramBuysPopper('party popper')
           .then(birthdayPlanStaysOn)  // Woohoo! 🎉🎉🎉

but still there is a catch what if ram says he missed or the popper went out of stock that day.

In that case you need to follow your contingency plan called as .catch

 ramBuysPopper('party popper')
           .then(birthdayPlanStaysOn)  // Woohoo! 🎉🎉🎉
           .catch(err=> { console.log(err) })

Constructing a promise

We can make a promise using the syntax below

const promise  = new Promise((resolve,reject)=> {
// do something
})

if the promise is called the value passed in the resolve returned is the paramenter of the then in the next line that can bee see in the below code

const promise = new Promise((resolve,reject) => {
    return resolve(23)
}).then(data => {
   console.log(data)
})
// this would be giving us 23

if the promise called is failed so the code goes in the catch block

const promise = new Promise((resolve, reject) => {
  // Note: only 1 param allowed
  return reject('💩💩💩')
})

// Parameter passed into reject would be the arguments passed into catch.
promise.catch(err => console.log(err)) // 💩💩💩
const ramGetsPartyPopper = (popper) => {
return new Promise((resolve, reject) => {
   setTimeout(() => {
    if (popper === 'party popper') {
      return resolve("party popper") 
      } else {
        reject ('No party popper')
      }
    }, 1000)
  }) 
}

const promise = ramGetsPartyPopper('demo').then((data)=>{ console.log(data) })
// console.log(promise)

we can also add a catch block to the above code block in order to get hold of wrong values if passed .

Promises Vs callback's

lets list down some main reasons why people use promises over call backs

  1. promises allows us to write less nested code
  2. promises allows us to visualize the code
  3. promises allows us to handle all the errors in a single code block in the bottom

In short, promises are rad. It helps you write asynchronous code without taking a step into callback hell.

Although you probably want to use promises whenever you can, there are cases where callbacks makes sense too. Don’t forget about callbacks 😉.