Simulating finally with the promise API
In a previous recipe, we saw how catch
can be used to handle errors, whether a promise has rejected, or a callback has thrown an error. Sometimes, it is desirable to execute code whether or not an error state has been detected. In the context of try
/catch
blocks, the finally
block can be used for this purpose. We have to do a little more work to get the same behavior when working with promises
In this recipe, we'll see how a final then
call to execute some code in both successful and failing fulfillment states.
Getting ready
This recipe assumes that you already have a workspace that allows you to create and run ES modules in your browser. If you don't, please see the first two chapters.
How to do it...
- Open your command-line application and navigate to your workspace.
- Create a new folder named
3-08-simulating-finally
. - Copy or create an
index.html
that loads and runs amain
function frommain.js
. - Create a
main.js
file with amain
function that logs out messages...