QUESTION: Что такое Promise?
A Promise in JavaScript is a special object used to represent the successful or failed completion of an asynchronous operation and its resulting value. A promise can be thought of as a guarantee to return some result in the future: you do not receive the data instantly, but you know that it will appear later, or you will receive an error notification.
At any given moment, a promise is in one of three possible states. The initial state is pending, when the asynchronous task is still running and the result is not yet known. If the operation completes successfully, the promise transitions to the fulfilled state, returning the resulting value. If an error occurs, the promise transitions to the rejected state, returning the reason for the failure. It is important to note that once a promise has transitioned to the fulfilled or rejected state, its status can never change again.
To work with promise results, special instance methods are used: then(), catch(), and finally(). The then() method accepts two callback functions: the first runs when the promise is successfully fulfilled, and the second when it is rejected. The catch() method is convenient syntactic sugar for error handling and is called if the promise was rejected. The finally() method runs in any case after the promise finishes its work, regardless of its success or failure, which is useful for cleaning up resources or hiding loading indicators.
The main advantage of promises over old callbacks is their ability to chain. You can call the then() method sequentially, passing the result of one asynchronous operation into the input of the next. This allows you to write clean, flat, and easily readable code, completely avoiding the problem of deep function nesting.