[ES2015] Promises

Promises

Promises are like callback functions, but so much better. Promises are meant to save you from callback hell.

ES6 feature, started out as libraries. Natively supported in all modern browsers.

A promise is a pattern for handling asynchronous operations. The promise allows you to call a method called “then” that lets you specify the function(s) to use as the callbacks.

A promise is an eventual value.

three states

  • pending
  • fulfilled or resolved
  • rejected

Now of course the more levels of nesting we have, the harder the code is to read, debug, maintain, upgrade, and basically work with. This is generally known as Pyramid of Doom or Callback Hell. Also, if we needed to handle errors, we need to possibly pass in another function to each xhrGET call to tell it what it needs to do in case of an error. If we wanted to have just one common error handler, that is not possible.

Notes

  • Promises are objects
  • Promises compose
  • Instead of having separate callback functions to deal with resource loads, you can just deal with them all in Promises with .all, which takes an array of resources.