Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson

Already subscribed? Sign In

Autoplay

    Create a Rejected Promise in JavaScript with Promise.reject()

    Marius SchulzMarius Schulz
    javascriptJavaScript

    You can use the Promise.reject() method to create a promise that is rejected with the given reason.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    Instructor: 00:00 Here is the code from the previous lessons again. We show a spinner while the data is loading and once we've fetched all the films from the API, we show a list of films. Now, if we access an endpoint that doesn't exist such as the movies endpoint, this response is not going to have an http success status code.

    00:17 Therefore, the OK property is going to be set to false. In this case, we're throwing an error. Whenever we throw an error within the fulfillment handle of this then call, the promise that is returned from the then call is rejected. Now instead of throwing, we could have explicitly returned a rejected promise.

    00:36 We can create a rejected promise by calling the promise.reject method. We pass to it the reason why the promise is rejected. Let's go ahead and see this code in action. We're going to head over to the browser, open the console, refresh the page, and sure enough, we see the error unsuccessful response.

    00:57 In addition to the error message, we also see a stack trace of the error. This is because we've rejected the promise with an instance of error. If we had rejected it with a plain string instead, we would not see the stack trace on the console.

    01:12 I recommend you always use a proper error instance when you return a rejected promise or throw an error in a promise chain. The stack trace that you're going to see in the console can be very helpful for debugging, especially in bigger applications. It also makes error handling a bit simpler if you know that you always have a proper error object.

    Discuss

    Discuss