Consuming Promises

Consuming Promises

  • While knowing how to construct a promise is useful, most of your interactions with promises will be spent consuming (or using) Promises

  • Put another way, you’ll be handling Promise objects returned to you as the result of an asynchronous operation

  • These promises will start off pending but must settle eventually


Settling Promises

  • Promise objects offer a .then() function that allows us to dictate what should happen after the promise settles

  • .then() is a function that takes two callback functions as arguments; when the promise settles, the appropriate handler will be invoked with that settled value

    • onFulfilled: The first handler is the success handler, and it should contain the logic for the promise resolving

    • onRejected: The second handler is the failure handler, and it should contain the logic for the promise rejecting


Example #1: Settling Promises: Successfully resolving a promise

let promise = new Promise(function(resolve, reject) {
  setTimeout(() => resolve("done!"), 1000)
})

// resolve runs the first function in .then()
promise.then(
  result => console.log(result), // shows "done!" after 1 second
  error => console.log(error) // doesn't run
)

JS Bin on jsbin.com


Example #2: Settling Promises: Rejecting a promise

let promise = new Promise(function(resolve, reject) {
  setTimeout(() => reject(new Error("Whoops!")), 1000)
})

// reject runs the second function in .then
promise.then(
  result => console.log(result), // doesn't run
  error => console.log(error) // shows "Error: Whoops!" after 1 second
)

JS Bin on jsbin.com