Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialGeorge Roberts
Full Stack JavaScript Techdegree Student 8,474 PointsWhy is a throw statement not required when new Error('...') is passed to Promise.reject()?
Hi, I'm just curious why, when new Error('...')
is passed to Promise.reject()
below, it doesn't need to be preceded by the throw
statement? Thanks
function checkStatus(response) {
if (response.ok) {
// console.log(Promise.resolve(response));
return Promise.resolve(response);
} else {
return Promise.reject(new Error(response.statusText));
}
}
1 Answer
KRIS NIKOLAISEN
54,971 PointsFrom MDN the syntax is:
Promise.reject(reason);
and returns a promise.
Description
The static Promise.reject function returns a Promise that is rejected. For debugging purposes and selective error catching, it is useful to make reason an instanceof Error.
From MDN on error
The Error object can also be used as a base object for user-defined exceptions
So errors don't have to be thrown to be useful. I would think in this case if you could throw the error you would no longer be returning a promise
This stack overflow may also be of interest as it discusses reject Vs. throw.
George Roberts
Full Stack JavaScript Techdegree Student 8,474 PointsGeorge Roberts
Full Stack JavaScript Techdegree Student 8,474 PointsThanks, your last sentence made it clear to me. Also found this within the stack overflow article which helped solidify it for me: "TLDR: A function is hard to use when it sometimes returns a promise and sometimes throws an exception. When writing an async function, prefer to signal failure by returning a rejected promise".