Member-only story

How is the finally method of Promise implemented?

Beck Moulton
9 min readJul 10, 2023

--

Have you ever encountered such a problem in your usual work: you need to send a network request, but whether the request succeeds or fails, you need to perform some cleaning work, such as hiding the loading animation.

You may be wondering, does JS provide a mechanism that allows you to execute some code logic during asynchronous operations, regardless of success or failure?

The answer is of course yes — the finally method of Promise.

Promises are a solution for handling asynchronous operations in JS , which allows us to handle the results and errors of asynchronous operations in an elegant and predictable way. The finally method is a mechanism provided by Promises - regardless of whether the asynchronous operation succeeds or fails, the finally method will execute.

However, have you ever wondered how this finally method is implemented? How does it ensure that the specified code will be executed regardless of the outcome of the Promise?

To answer the two questions above, first, you need to have a basic understanding of promises.

If you are already familiar with the basics of Promises, you can skip this part and go directly to “ finally method implementation ".

Promise basis

Promises are a built-in object in JS that handles asynchronous operations. Promises have three states: pending, fulfilled, and rejected.

--

--

Beck Moulton
Beck Moulton

Written by Beck Moulton

Focus on the back-end field, do actual combat technology sharing Buy me a Coffee if You Appreciate My Hard Work https://www.buymeacoffee.com/BeckMoulton

No responses yet