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.

Author: Ankur

I am Enthusiastic about Learning new things and sharing my Knowledge. I like programming and have a pretty good background in Computer Science.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: