Promises..Promises! Flashcards
How do Promises work?
The executor runs automatically and attempts to perform a job. When it is finished with the attempt, it calls resolve if it was successful or reject if there was an error.
The promise object returned by the new Promise constructor has these internal properties:
1.) State — initially “pending”, then changes to either “fulfilled” when resolve is called or “rejected” when reject is called.
2.) Result — initially undefined, then changes to value when resolve(value) is called or error when reject(error) is called.
What are Handlers?
1.) .catch handles errors in promises of all kinds: be it a reject() call, or an error thrown in a handler.
2.) .then also catches errors in the same manner, if given the second argument (which is the error handler).
3.) We should place .catch exactly in places where we want to handle errors and know how to handle them. The handler should analyze errors (custom error classes help) and re-throw unknown ones (maybe they are programming mistakes).
4.) It’s OK not to use .catch at all, if there’s no way to recover from an error.
5.) In any case we should have the UN-handled rejection event handler (for browsers, and analogs for other environments) to track un-handled errors and inform the user (and probably our server) about them, so that our app never “just dies”.
Promise Methods…
There are 6 static methods of Promise class:
1.) Promise.all(promises) – waits for all promises to resolve and returns an array of their results. If any of the given promises rejects, it becomes the error of Promise.all, and all other results are ignored. 2.) Promise.allSettled(promises) (recently added method) – waits for all promises to settle and returns their results as an array of objects with: status: "fulfilled" or "rejected" value (if fulfilled) or reason (if rejected). 3.) Promise.race(promises) – waits for the first promise to settle, and its result/error becomes the outcome. 4.) Promise.any(promises) (recently added method) – waits for the first promise to fulfill, and its result becomes the outcome. If all of the given promises are rejected, AggregateError becomes the error of Promise.any. 5.) Promise.resolve(value) – makes a resolved promise with the given value. 6.) Promise.reject(error) – makes a rejected promise with the given error.
Of all these, Promise.all is probably the most common in practice.