Javascript - Creating a Promise

Introduction

Promises are created using the new Promise() constructor that accepts a function that takes two parameters:

  • resolve - a function that is called with the future value when it's ready, that is, when the promise is fulfilled;
  • reject - a function that is called to reject the promise if it can't resolve the future value.

The executor initiates some asynchronous work and then, once that completes, calls either the resolve or reject function to resolve the promise or else reject it if an error occurred.

A simple Promise looks like this:

const p = new Promise((resolve, reject) => { 
    if (/* some condition */) { 
        resolve(/* some value */);  // fulfilled successfully 
    } else { 
        reject(/* some reason */);  // error, rejected 
    } 
}); 

The second method (reject) is optional, and you can create a promise with only the resolve method.

new Promise(resolve => resolve()) // promise is fulfilled 
new Promise((resolve, reject) => reject()) // promise is rejected 

You can also create an immediately resolved promise using:

const sayHello = Promise.resolve("hello!"); 

You can also reject a promise using Promise.reject(value).

Usually, a promise will resolve to some value that could be a result from an HTTP request, animation, or some other asynchronous operation.

A promise, once created, can only be either fulfilled or rejected.

Related Topic