如何在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
,但是这并没有改变任何东西。
我该如何编写一个处理err1
和err2
error 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 })