如何在Q.then()callback中传播嵌套错误

我觉得这应该很容易,但我一直在挣扎一段时间。

我有看起来像这样的代码(显然这是一个简化的例子)。

getPromise(param1, param2) .then(function (results) { // do something that causes an error: var err1 = new Error() throw err1; }) .then(function (results) { getAnotherPromise(param1) .then(function (res) { // do something else that might cause an error: var err2 = new Error() throw err2; }) }) .then(function (results) { // deal with the results of above code }) .fail(function (error) { // handle error }) 

问题是, err2永远不会导致.fail处理程序被调用。 err1按预期处理,但err2只是消失。 我尝试添加另一个.fail处理程序后.fail负责生成err2 ,只是重新投入err2 ,但是这并没有改变任何东西。

我该如何编写一个处理err1err2error handling程序?

Q不能处理嵌套诺言,除非你return它。 所以,你的代码应该是这样的:

 getPromise(param1, param2).then(function (results) { // do something that causes an error: throw new Error('error 1'); }).then(function (results) { return getAnotherPromise(param1).then(function (res) { // do something else that might cause an error: throw new Error('error 2'); }) }).then(function (results) { // deal with the results of above code }).fail(function (error) { // handle error }) 

实际上,承诺值是错误的,所以你可以用下面的方式编写你的代码:

 getPromise(param1, param2).then(function (results) { // do something that causes an error: throw new Error('error 1'); }).then(function (results) { return getAnotherPromise(param1) }).then(function (res) { // do something else that might cause an error: throw new Error('error 2'); }).then(function (results) { // deal with the results of above code }).fail(function (error) { // handle error })