Promise.finally

Description: The `Promise.finally` method is an addition to the Promise API in JavaScript that allows executing a block of code once a promise has been completed, whether it was resolved successfully or rejected. This method was introduced in ECMAScript 2018 (ES9) and provides a convenient way to perform cleanup or finalization tasks without duplicating code in the success (`then`) and error (`catch`) handlers. The syntax of `finally` is straightforward: it is invoked on a promise and accepts a function as an argument, which will be executed at the end of the promise’s lifecycle. This is particularly useful in situations where certain actions need to be guaranteed, such as closing database connections or releasing resources, regardless of the outcome of the asynchronous operation. Additionally, `finally` does not affect the original promise’s value; that is, if `finally` is called, the returned value from the promise remains intact, allowing for further promise chaining if necessary. In summary, `Promise.finally` enhances code readability and maintainability by centralizing finalization logic in one place.

History: The `Promise.finally` method was introduced in ECMAScript 2018 (ES9) as part of an effort to improve the Promise API in JavaScript. Prior to its inclusion, developers often had to duplicate code in `then` and `catch` handlers to perform cleanup tasks, which could lead to errors and less clean code. The addition of `finally` allowed developers to handle finalization more efficiently and clearly.

Uses: The `Promise.finally` method is primarily used to execute cleanup or finalization code after a promise has been completed, regardless of its outcome. This is useful in situations such as closing database connections, releasing resources, or performing logging actions. By centralizing finalization logic, it improves code readability and maintainability, avoiding duplication of logic in promise handlers.

Examples: A practical example of `Promise.finally` would be the following: when making a request to an API, `finally` can be used to hide a loading indicator after the request has completed, regardless of whether it was successful or failed. Example: `fetch(url).then(response => response.json()).catch(error => console.error(error)).finally(() => { loadingIndicator.style.display = ‘none’; });`.

  • Rating:
  • 3.1
  • (14)

Deja tu comentario

Your email address will not be published. Required fields are marked *

PATROCINADORES

Glosarix on your device

Install
×
Enable Notifications Ok No