JamesTheHacker JamesTheHacker - 1 year ago 157
Javascript Question

Why does Promise.reject() require a return?

In the following code the

doesn't work unless I specifically use
return Promise.reject(...)
. Why is this?

Promise.resolve('Promise 1 Done')
.then(function(result) {
return 'Promise 2 Done'
}).then(function(result) {
let j;
try {
j = JSON.parse("invalid will throw");
} catch(err) {
Promise.reject('Could not parse JSON');

}).catch(function(err) {

Answer Source

Promise.reject creates a value, it does not throw an exception that breaks from the function like throw does. If you don't return that value, it will be ignored and the control flow continues.

Given you are inside a promise callback, you could (and possibly should) instead use

throw new Error('Could not parse JSON');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download