According to this Stack Overflow answer here, there is no difference between using reject
and throw
within a promise to trigger a rejection.
However, I have found that, depending on the structure of an external module, throwing an error doesn't always trigger the catch
block.
This is my code in index.js
:
try {
const service = require('./services/patreon.js');
await service.start();
} catch(err) {
console.log('Caught!');
}
And here is my code in patreon.js
:
function start() {
return new Promise(async (resolve, reject) => {
throw new Error('Oh no!');
});
}
module.exports = {
start: start
}
My expected behavior is that my try/catch block would handle the thrown error and I would see "Caught!" in my console ouput. Instead, my try/catch does not handle the error and I end up with an unhandledRejection.
Interestingly, if I re-structure my module.exports in patreon.js
I can fix this and my try/catch block will handle the error:
Update index.js
:
try {
const service = require('./services/patreon.js');
await service();
} catch(err) {
console.log('Caught!');
}
Update patreon.js
:
module.exports = () => {
return new Promise(async (resolve, reject) => {
throw new Error('Oh no!');
});
}
With the above updates, my try/catch works perfectly but I no longer have the ability to export more than just a function.
The other solution is to simply reject()
the promise instead of throw
- and this works fine in both examples but for personal preference and code cleanliness I would rather be able to throw
.
So my question is, why can't I use throw
when my module is structured in the way shown in my first example? In both cases, I end up with the exact same thing: a function that returns a promise.