Creating Promises

Creating Promise Objects

  • To create a new Promise object, we use the new keyword and the Promise constructor method:

        const executorFunction = (resolve, reject) => { }
    
        const myPromise = new Promise(executorFunction)
        
    
  • The Promise constructor method takes a function parameter called the executor function which runs automatically when the constructor is called

  • The executor function generally starts an asynchronous operation and dictates how the promise should be settled

We’ll talk more about constructor methods in a later lesson


Executor Function

  • The executor function has two function parameters:

    • resolve(): If invoked, resolve() will change the promise’s status from “pending” to “fulfilled”, and the promise’s resolved value will be set to the argument passed into resolve()

    • reject(): If invoked, reject() will change the promise’s status from “pending” to “rejected”, and the promise’s rejection reason be set to the argument passed into reject()

  • The resolve() and reject() functions aren’t defined by the programmer; when the Promise constructor runs, JavaScript will pass its own resolve() and reject() functions into the executor function


Example: Basic structure of an executor function

  // example below is meant to show structure only, this is not working code

  const executorFunction = (resolve, reject) => {
    if (someCondition) {
        resolve('I resolved!')
    } else {
        reject('I rejected!')
    }
  }

  // pass the executor function as a parameter to the Promise constructor
  const myPromise = new Promise(executorFunction)

  

In the example above, myPromise resolves or rejects based on a simple condition, but, in practice, promises settle based on the results of asynchronous operations.; for example an API request to another service may “fulfill” by returning the desired data or it may “reject” if an error occurred during the request


Example: Creating a Promise

  const inventory = {
    sunglasses: 202,
    pants: 421,
    shirts: 1344
  }

  // Write your code below:
  const myExecutor = (resolve, reject) => {
    if (inventory.sunglasses > 0) {
      resolve('Sunglasses order processed.')
    } else {
      reject('That item is sold out.')
    }
  }

  const orderSunglasses = () => {
    return new Promise(myExecutor)
  }

  const orderPromise = orderSunglasses()

  // print out the promise object
  console.log(orderPromise)
  
  • Run the jsbin below and open up chrome developer tools and inspect the promise object that is being printed to the console. Can you identify the current status of the promise?

JS Bin on jsbin.com


Alternative Syntax

The most common syntax for constructing promise involves combining the executor function with the Promise constructor

  const inventory = {
    sunglasses: 202,
    pants: 421,
    shirts: 1344
  }

  const orderSunglasses = () => {
    // Most common syntax for creating promises
    return new Promise((resolve, reject) => {
      if (inventory.sunglasses > 0) {
        resolve('Sunglasses order processed.')
      } else {
        reject('That item is sold out.')
      }
    })
  }

  const orderPromise = orderSunglasses()

  // print out the promise object
  console.log(orderPromise)
  

JS Bin on jsbin.com