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

Marius Schulz
InstructorMarius Schulz
Share this video with your friends

Social Share Links

Send Tweet
Published 6 years ago
Updated 4 years ago

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

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.

Victor
Victor
~ 6 years ago

What is the advantage of returning a rejected promise rather than just throwing an error (as in previous example). The stack trace is available in both cases, just not sure I fully understand the purpose of Promise.reject

Marius Schulz
Marius Schulzinstructor
~ 6 years ago

@Victor: Within an async function, you can decide to go with either approach; both throwing an error and returning a rejected promise will result in a rejected promise being returned from the method.

However, there's a difference in behavior in a non-asynchronous function (one that's not declared using the async keyword). If you throw an error, such a function will not return a rejected promise — it will let the error bubble up the call stack until the nearest catch block (if any). Returning a rejected promise, on the other hand, will not cause an error to be thrown.

Markdown supported.
Become a member to join the discussionEnroll Today