I know that stackoverflow is full of similar question and I've read a lot of them.
From what I got a throw
inside a promise should reject it, as I can read in the documentation:
If the executor throws an exception, its value will be passed to the reject resolving function.
But even after read a lot of post about promises and throw I still don't understand the snippet of code I'm pasting and why it happens.
function foo(a, b, cb) {
setTimeout(() => {
cb('Inner error *!?"$%&#@"');
}, 0);
}
const getThePromise = () => {
return new Promise((resolve, reject) => {
const cb = (err) => {
/* >>> ************ */
throw err; // catch not called
// reject(err); // catch called
/* ************ <<< */
}
foo('foo', 'dudee', cb);
});
}
getThePromise()
.catch((err) => {
console.log('CATCH:', err);
})
.then((res) => {
console.log('then...');
})
I don't understand why if I use the throw
the .catch
of the promise is not called but if I use the reject
it is called.
Just for sake of clarification I'm using Node.js v6.2.2 in a Mac OS/X 10.11 but I don't think it could be also a browser issue.
.error((err) => { console.log('ERROR:', err); })
too there – Blimeyerror
function – Bankrollthrow
rejects promise if it's called synchronously only. remove yoursetTimeout
and it will work. In async case usereject
. – Spermatocytenew Promise(() => {throw new Error('test')}).catch( e => console.log(e))
– Retinuereject
method. – Kistner