- [Instructor] In the last lesson, we introduced
the Promise object and saw how it could be used
to handle asynchronous code.
What we didn't implement with this Promise object
is what happens if something goes wrong.
So within the Promise itself, we get to send it the code
that it will invoke and anywhere this code
can cause an error.
I can actually throw a new error and
we'll call this error ar.
So let's just assume that an error happens
anywhere within our Promise.
That means when we come over here to run the code,
I do note that, oh, we see an error.
Well that makes sense because we threw an error.
Let me go ahead and drag this out so we can
see this full error here.
What you'll notice is we see an unhandled Promise rejection,
that means that an error has occurred within a Promise
but we didn't handle it.
If I look at this Promise that I invoked in the last lesson,
we can see several then methods but there
is nothing here to handle an error.
Within Promises, we can handle the error
or when something goes wrong using a catch.
So I'm going to go ahead and chain a catch method
onto here and when we do the catch method,
our error itself will be passed,
so I'll go ahead and console.log
and here we're going to go ahead and place the error
and we'll go ahead and output the error.message
So now when I go ahead and save this,
come over to the terminal, clear the screen
and run the current script, we notice that we don't see
a huge error because we handled the error that has occurred
in the Promise, we've wired up a function
to deal with that error.
Now we're just logging it to the console here
but we can easily add this error to a reporter
or do something else with the object.
Now the neat thing about Promise is that
we don't have to have an error to have a rejection.
We can simply invoke the rejects method anytime we want.
So if I were going to say, if (seconds > 3),
I can simply call rejects to reject the Promise.
When I reject this Promise, I'm going to actually pass
a new error and in this error, we will
output the number of seconds is too long,
so that's our new error message.
So if an error occurs, then it can be handled
with the catch method but also if we invoke rejects,
we can pass an error to that catch method.
Let's go out to the terminal and run our file,
so we can see that we ended the first tick
and we have the long delay has ended and hello world
is returning 42, that is because
we've only waited one second
but what happens when we wait four seconds?
So I'm going to go ahead and send four to the delay
and run this code and we end the first tick
because we are dealing with an asynchronous action
and then we see that four is too long
so we rejected the Promise based on the value
for the seconds argument.
So if an error occurs, we can handle it with
that catch method but also if we reject
the Promise for any reason,
we can also handle that with the catch method.