Overview

A Promise object represents the future result of an asynchronous operation.

A promise is always in one of these states:

  • pending: initial state, not fufilled or rejected.
  • fulfilled: the operation completed successfully
  • rejected: the operation failed :(

Once instantiated, the Promise is said to be in the “pending” phase. Once the phase is “fufilled”, a callback can be applied to the resolved value, which can return a new promise. Promises allows us to write asynchronous code in a synchronous way.

You can instantiate a new Promise() object and pass it a callback to perform async computations. This callback has two arguments: resolve and reject. Both of which, are passed later passed as callbacks in the .then() method.

When the Promise has “fufilled”, the resolve callback will be applied to a value. If the Promise returns an error, the reject callback is invoked.

Where do the resolve and reject callbacks come from?

The resolve callback is passed through the Promise object’s .then() method.

The reject callback is passed through the Promise object’s .catch() method.

Code Example

1) Create a new promise:

Note: randomIntApi just returns an integer after some seconds

const myPromise = new Promise(function (resolve, reject) {
  // async api call or some async computations
  randomIntApi((value) => {
	  resolve(value)
	  reject("I have failed")
  })
})

2) Promise is invoked, and is pending… once complete will invoke the callback passed to .then()

3) Pass a callback to the Promise’s .then() method which will be applied on the resolved value:

myPromise.then((value) => {
	// apply callback to resolved value
	console.log(value)
})


Promise in action using .fetch() API

Note: fetch api returns a promise that resolves to a reponse

const resPromise = fetch('https://api.github.com/users/hzhu')

resPromise.then((res) => {
	//callback to handle response
})

Chaining Promises

As an aside, if you return another Promise object in the callback, you can chain Promises:

const myPromise = new Promise(...)
const yourPromise = new Promise(...)
const userPromise = fetch('https://api.github.com/users/hzhu')

myPromise.then((results) => {
	// handle results of myPromise
	return yourPromise
}).then((resultOfYourPromise) => {
	// handle results of yourPromise
	return userPromise
}).then((response) => {
	// handle response from github
})