In the previous recipe, we saw how to use resolve
to provide a result from a successfully fulfilled promise. Unfortunately, the code doesn't always run as expected. Network connections can be down, data can be corrupted, and uncountable other errors can occur. We need to be able to handle those situations as well.
This recipe demonstrates how to use reject
when errors arise.
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.
- Open your command-line application and navigate to your workspace.
- Create a new folder named
3-03-rejecting-promise-errors
. - Copy or create an
index.html
that loads and runs amain
function frommain.js
. - Create a
main.js
file that creates a promise, and logs messages before and after the promise is created and when the promise is fulfilled:
new Promise(function (resolve) { resolve(); }).then(function...