Understand the what, why and how of Promises in Javascript

What are Promises? Why to use them?

Say you are a celebrity blogger and people are waiting for your next blog. You promise to notify them once the blog is ready. You take their emails and once your blog is done notify them via email.

A promise in Javascript works similarly. If you have an asynchronous operation you can use a promise to let the consumer know about its outcome.

It’s a placeholder for an asynchronous operation outcome. It’s an object which has a state and a value.

let promise = new Promise(function (resolve, reject) {
  // DB call
  if(call was success) {
    resolve(value)
  }
  reject(error)
})

Promise has an executor function with two parameters – resolve and reject. These parameters are predefined by the javascript engine.

Promise object has a state and a result. State can be pending, fulfilled or rejected. Value can be undefined, value or error.

Problem with Promises – a chain of promises makes the code complex.