The goal of this book is to explain how JavaScript promises work while giving practical examples of when to use them. All new asynchronous JavaScript APIs will be built with promises going forward, and so promises are a central concept to understanding JavaScript as a whole. My hope is that this book will give you the information you need to successfully use promises in your projects.
Nicholas C. Zakas is a front-end consultant, author, and speaker. He worked at Yahoo! for almost five years, where he was front-end tech lead for the Yahoo! homepage and a contributor to the YUI library. He is the author of Maintainable JavaScript (O’Reilly, 2012), Professional JavaScript for Web Developers (Wrox, 2012), High Performance JavaScript (O’Reilly, 2010), and Professional Ajax (Wrox, 2007). Nicholas is a strong advocate for development best practices including progressive enhancement, accessibility, performance, scalability, and maintainability.
“Each promise goes through a short lifecycle starting in the pending state, which indicates that promise hasn’t completed yet. A pending promise is considered unsettled. The promise in the previous example is in the pending state as soon as the fetch() function returns it. Once the promise completes, the promise is considered settled and enters one of two possible states (see Figure 1-1): 1. Fulfilled: The promise has completed successfully. 2. Rejected: The promise didn’t complete successfully due to either an error or some other cause.”
“An internal [[PromiseState]] property is set to “pending”, “fulfilled”, or “rejected” to reflect the promise’s state. This property isn’t exposed on promise objects, so you can’t determine which state the promise is in programmatically. But you can take a specific action when a promise changes state by using the then() method.”
“Promises also have a catch() method that behaves the same as then() when only a rejection handler is passed.”
“To go along with then() and catch() there is also finally(). The callback passed to finally() (called a settlement handler) is called regardless of success or failure. Unlike the callbacks for then() and catch(), finally() callbacks do not receive any arguments because it isn’t clear whether the promise was fulfilled or rejected”
“A promise can only be resolved once, so if you call resolve() more than once inside of an executor, every call after the first is ignored.”
“The Promise.resolve() method accepts a single argument and returns a promise in the fulfilled state. That means you don’t have to supply an executor if you know the value of the promise already.”
“You can also create rejected promises by using the Promise.reject() method. This works like Promise.resolve() except the created promise is in the rejected state”