Let's now learn how to handle exceptions that happen inside a promise. In the event of such a situation, we must reject the promise using a special reject function, which automatically falls into the second parameter of the promise function:
let promise = new Promise(function(resolve, reject) {
setTimeout(function() {
...
}, 3000);
});
Inside the promise function, we must call
resolve
if everything went well,
or reject
if an exception occurred:
let promise = new Promise(function(resolve, reject) {
setTimeout(function() {
let isError = false;
if (!isError) {
resolve([1, 2, 3, 4, 5]); // a promise data
} else {
reject('error in promise'); // your error text
}
}, 3000);
});
Then, in the then
method, you must
pass not one, but two functions as
parameters: the first will work if the
promise fired properly (resolved),
and the second - if it fired with an error
(rejected):
promise.then(
function(result) {
console.log(result); // displays a promise result
},
function(error) {
console.log(error); // displays an error text
}
);
As a rule, the above code is written in a more compact way, like this:
promise.then(function(result) {
console.log(result); // displays a promise result
}, function(error) {
console.log(error); // displays an error text
});
Make an async code that will generate
random numbers from 0
to
5
. Wrap it all in a promise. Let
the promise return the result of dividing
one by the generated number. Let the
promise fail if a division by zero
occurs, and succeed in all other cases.