是否有一个处理程序方法,即fail的对应方法,类似success的方法,可以真正退出异步队列并继续进行正常的函数调用。
让我详细说明。比方说
getConnection()
.then(function(connection){
return self.getRecords() //some async routine, returns promise, does reject/resolve
})
.then(function(data){
return self.getDetail() //some async routine, returns promise, does reject/resolve
})
.then(function(data){ //I'm done here calling onResult, but this onResult may call several
self.onResult(data); //other functions down the road resulting in .fail() call
}) //I want to get out of this promise queue and continue with normal functions calls
.fail(function(info){
self.onFault(info); //any error onFault causes down the road shouldn't be q problem.
})
.done(function(){ //but this gets called all the time at end no matter success or fail
//release system resource like connection etc.
})
我试着在评论中解释这个问题,基本上我已经完成了self.getDetail()调用,一旦成功,我想退出promise队列,原因是,如果self.onResult(data)
之后出现问题,.fail()
也会被触发,因为它在某种程度上是依赖的。
我尝试将调用放在.done()
方法中,但无论成功还是失败,都会调用done()
。
我有一个失败的例程,它被.fail()
函数调用,但不知道是否有成功处理程序。
欢迎任何横向思考
编辑-在Barmar的评论之后,我们可以这样做吗。(getConnection返回承诺并拒绝/解析
connections.getConnection(function(c){
return self.getMaster(c) //async routine, returns promise, does reject/resolve
}, function(info){
self.onFault(info) //any failures in getMaster, any error in onFault shouldn't be q business
})
.then(function(data){
return self.getDetail() //async routine, returns promise, does reject/resolve
}), function(info){
self.onFault(info)} //any failures in getDetail, any error in onFault shouldn't be q business
})
.fail(function(info){ //btw any errors, onFault causes down the road shouldn't be q problem- same for above onFault calls
self.onFault(info) //do I need this after above fail routines for each call?
})
.done(function(){ //ok, once everything's done, get out of promise queue
self.onResult(self.data) //any problem onResult causes down the road, should be it's own business
}) //release routine
//异步队列、promise链等中的两个独立函数。这些函数中的任何错误都不应影响promise链或调用其故障处理程序。一连串的承诺本应在上面兑现。
onResult: function(data) {
console.log('do something with the data');
}
onFault: function(info) {
console.log('wonder what went wrong');
}
请建议编辑以上
我的主要要求是,onResult
、onFault
之后发生的任何事情都不应该是q库业务(fail
),他们现在(之后)应该自己处理
传递给then
的第一个函数本身就是一个成功处理程序。
操作的返回值,如:doSomething().then(function() { ... })
是一个新承诺,您可以始终将其存储在变量中,然后对使用多个独立的then
调用
var promise = someOperation().then(function(x) {
return doSomethingWith(x);
});
promise.then(function(processedX) {
// processedX is the return value of the function used to construct `promise`
// now for something completely different
}
promise.then(someOtherFunction);
你不需要无限期地连锁,你总是可以通过将中间的新承诺存储到变量中并在其他地方使用它们(可能多次)来"走出承诺链",并创建几个独立的链。
这样,您就可以在一个链中将fail
处理程序附加到一个相同的promise,而在另一个链中则不附加任何处理程序。在您的情况下,您希望将调用self.onResult
的处理程序的整个链存储在一个变量中,对该变量使用fail
处理程序,并使用同一变量继续执行其余代码。