在一个承诺里面callback里面

我知道,stackoverflow充满了类似的问题,我读了很多。

从我得到的承诺中throw应该拒绝它,因为我可以在文档中阅读:

如果执行者抛出一个exception,它的值将被传递给拒绝parsing函数。

但即使阅读了许多关于承诺的post后,我仍然不明白我正在粘贴的代码片段以及为什么会发生这种情况。

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

我不明白为什么如果我使用throw承诺的.catch没有被调用,但如果我使用reject它被称为。

为了说明起见,我在Mac OS / X 10.11中使用了Node.js v6.2.2,但是我不认为这也可能是一个浏览器问题。

你正在抛出你的错误在一个asynchronoussetTimeout调用,这将导致一个未被捕获的错误。 asynchronous代码不会与try-catch块在同一个上下文中执行。 这与promise API没有任何关系。 这只是JavaScript中asynchronous代码执行行为的一部分。

看看下面的例子。

 const asyncOperation = err => { try { setTimeout(function() { throw err; // will be dropped onto the event queue // until the call stack is empty // even if this takes longer than // a second. }, 1000); } catch (e) { console.log(e) // will not be called } } asyncOperation('Inner error *!?"$%&#@"')