我最近开始用coffeescript/javascript编写承诺代码,我很喜欢它。我不明白的一件事是如何用承诺来处理流控制。考虑使用Q的下列代码。
outerFunction = ->
Q()
.then ->
doSomethingAsync
.then (result) ->
return result if result is someSpecialValue
#do I really have to continue this chain or nest my promises in a new promise chain?
...
.then ->
...
.then ->
...
我想早点回到来电者那里。这有可能吗?
我不想用神奇的例外来控制流量。我需要这样做还是有更好的方法?
...
.then (result) ->
return result if result is someSpecialValue
return Q()
.then ->
...
.then ->
...
发布于 2016-01-30 04:57:58
这里有一个更完整的答案,返回呼叫者是不可能的。因为承诺在异步运行..。换句话说,当承诺开始生效时,调用方已经返回。所以不可能返回到调用方,因为调用者已经离开了。
如果您想放弃承诺,只需使用参数调用this.reject()
即可拒绝。它将陷入catch
的承诺中。如果您不希望catch
子句处理更多的then
,也可以使用它来处理它。然后,在某一时刻,这将导致承诺的失败。
它可能做不到您想做的事情,因为您必须至少在最终的catch
上处理错误,或者为什么您很早就离开了承诺。但即使是catch
也是一个承诺。
outerFunction = ->
Q()
.then ->
doSomethingAsync
.then (result) ->
if error
this.reject(result)
return result if result is someSpecialValue
.then ->
...
.then ->
...
.catch (error) ->
console.log("Handling error", error)
这里有更多关于承诺的文档:http://promisejs.org/,这是一个很好的阅读。
我希望您理解,using
拒绝就像试图通过引发异常来提前退出一个函数--一对堆叠的函数。我不鼓励这样做,因为这可能是相当可怕和难以理解背后的逻辑。如果您必须尽早退出承诺,即使没有例外或错误,那么您可能需要重新考虑您的流程。
相反,你能做的是:
outerFunction = ->
Q()
.then ->
doSomethingAsync
.then (result) ->
if return_now
return result if result is someSpecialValue
return Q()
.then ->
...
.then ->
...
.then ->
...
您可以返回您的结果或返回将继续流程链的承诺。
https://stackoverflow.com/questions/35098110
复制相似问题