【发布时间】:2014-11-08 19:01:41
【问题描述】:
是否有一个处理程序方法,与失败相对应,类似于成功,可以真正退出异步队列并继续正常的函数调用。
让我详细说明。比方说
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.
})
我试图在 cmets 中解释问题,基本上我已经完成了 self.getDetail() 调用,一旦成功,我想退出承诺队列,原因,如果 self.onResult(data) 有问题的方式之后,.fail() 也会被触发,因为它是它的依赖项。
我尝试将我的调用放入 .done() 方法中,但无论成功还是失败,done() 都会被调用。
我有一个失败的例程,它被 .fail() 函数调用,但不知道是否有成功的处理程序。
欢迎任何横向思考。
编辑 - 在 Barmar 的 cmets 之后,我们可以这样做吗? (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
//异步队列中的两个独立函数,承诺链等。这些函数中的任何错误都不应影响承诺链或将其称为失败处理程序。承诺链应该在那里完成。
onResult: function(data) {
console.log('do something with the data');
}
onFault: function(info) {
console.log('wonder what went wrong');
}
请为上述编辑提出建议
我的主要主要要求,onResult、onFault 之后发生的任何事情都不应该是 q 图书馆业务 (fail),他们现在应该自己处理(之后)
【问题讨论】:
-
.then()有两个参数:第一个是成功函数,第二个是失败函数。 -
哦,我明白了,让我在我的编辑中为您的 cmets 重写一些内容
-
this question 表示
.then相当于 jqXHR 的.success。您确定getConnection()首先报告失败吗?
标签: javascript promise q