Promises - 401-advanced-javascript-billybunn/seattle-javascript-401d29 GitHub Wiki

Largely based on a reading of You Don't Know JS: Async & Performance, Chapter 3: Promises by Kyle Simpson

Summary of Promises

So at this point, we've learned about using callbacks for async JavaScript. This article summarizes that idea nicely:

For JavaScript to know when an asynchronous operation has a result (a result being either returned data or an error that occurred during the operation), it points to a function that will be executed once that result is ready. This function is what we call a “callback function”.

This is great for some stuff, but when you need the information that one callback will return in order to do some other stuff (like make another request to an API), you run into an ugly mess pretty quick of nesting these async callback functions. This is commonly known as "Callback Hell".

Promises are a great way to avoid this sort of code organization. Promises are objects that represent a future value, or a value that may or may not be available yet, but will be eventually. We might still rely on the actual return value of a promise to do something else, but we can pass in a promise regardless, since it acts like a "proxy" for the actual data. You can also attach callbacks to promises that are invoked when the promise's state changes.

Resources

Read

Watch

  • what the heck is the event loop anyway

Bookmark

  • Mock Functions
  • Manual Mocking