JamesTheHacker JamesTheHacker - 3 months ago 14
Javascript Question

Why does Promise.reject() require a return?

In the following code the

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

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

console.log(result);
}).catch(function(err) {
console.log(err);
});

Answer

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');