Nischit Shetty's Blog

Nischit Shetty's Blog

Introduction to Promise in JavaScript ES6

Introduction to Promise in JavaScript ES6

Promise in javascript is one of the commonly asked questions in JS based interviews these days and also a very helpful concept to learn in javascript.

Promise : What is it?

Promise are similar to real life promise. You always make a promise for a event in future.

Suppose you make a promise to attend a friend's upcoming birthday. There are three states for this promise

  1. Pending state - Till the birthday event occurs, it will be in pending state.

  2. Successful state - The birthday finally comes and you have successfully kept your promise.

  3. Rejected state - The birthday happened but you weren't able to attend and keep your promise due to some issue.

Promise : The Code

new Promise( /* executor */ function(resolve, reject) { ... } );

Promises are used for asynchronous operations where a wait period is usually involved like API calls, I/O operations, file handling etc.

let attendBirthday = true

promise1 = new Promise(function(resolve, reject) {
  if (attendBirthday) {
    resolve("Happy Birthday ");
  } else {
    reject("Sorry I wasnt able to attend");

The resolve status gives out value as "Happy Birthday" since the promise is resolved successfully. However, in case the promise returns reject state the value "Sorry I wasnt able to attend" would be returned.

Chaining promise would be covered in the next post.

Share this