Lesson 30. Promises
After reading lesson 30, you will be able to
- Use promise-based libraries to fetch asynchronous data
- Do basic error handling for promises
- Memoize asynchronous calls using Promise.resolve
- Combine several promises into one
A promise is an object that represents an eventual value. You can access this eventual or future value by calling .then() on the promise and supplying a callback function. The promise will eventually invoke this callback with the value. If the promise is still waiting for the value (the promise is in a pending state), then the promise will wait until the value is ready or has loaded (at which point the promise enters the resolved state) before invoking the callback with the value. If the promise has already resolved, then the callback will be invoked right away.[1]
1Not immediately. The callback will be added to the event loop, similar to a setTimeout with a delay of 0.
Consider this
Asynchronous values in JavaScript were traditionally accessed by passing around callback functions that would get invoked once the data was ready. This is limiting because only the object that has a reference to the callback gets notified when the value is ready. What if instead of passing around a callback, you could pass around a value that represents what the asynchronous value will eventually become? How would this work?