JavaScript·100 questions

QUESTION: Как обрабатывать ошибки Promise?

Answer

Error handling in promises in JavaScript is a fundamental skill for building stable and reliable web applications. The main tool for this is the .catch(error => {}) method, which catches any failures and rejections arising in previous steps of the asynchronous chain. An alternative option is passing a second argument to the .then(null, onRejected) method, but in practice, the first approach is used much more often due to its clarity and ease of reading code.

The main advantage of the catch method is that catch catches all errors in the chain, regardless of at which specific stage of asynchronous execution the failure occurred. This allows for centralized exception handling rather than writing cumbersome handlers for each individual step. If an unexpected situation arises during code execution, execution is redirected to the nearest catch block.

It is important to remember the situation where a promise is rejected, but no error handling is provided for it. In modern runtimes, this leads to the occurrence of an unhandledrejection event on the global object, which can cause a crash in Node.js or write a warning to the browser console. To avoid such problems, it is always recommended to end promise chains with a call to the catch method.

To run code that must be executed in any case—regardless of whether the promise finished successfully or with an error—the finally() method is used. It accepts a callback function without arguments and is great for cleaning up resources, closing database connections, or hiding a loading indicator on the user interface. A competent combination of all these tools allows you to fully control the lifecycle of asynchronous operations in your projects.

Was this answer helpful?

More questions in this topic

Related questions from other topics