【发布时间】:2016-05-07 23:46:09
【问题描述】:
我最近开始用 coffeescript/javascript 编写 Promise 代码,我喜欢它。我不明白的一件事是如何使用 Promise 处理流控制。考虑以下带有 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 ->
...
【问题讨论】:
-
无法返回调用者。
-
IIRC,通常当您附加
then时,您将返回原始承诺,因此当原始承诺返回时,它们都会同时触发。它们不是按顺序进行的。 -
@Andrew 在每个 promise 中转换值时并行化如何工作?我是
-
考虑获取 response.json() 的返回位置,然后我是链的下一个承诺获取 json 格式的响应作为其参数
-
@Andrew 承诺中没有并行化。它们只是异步完成的。它不像多线程。组织异步 IO 流非常有用。您不必等待 IO 来处理其他 IO。请记住,JS 在单个线程中工作。所以根本没有并行化。
标签: javascript coffeescript q