【问题标题】:Promises and flow control: Early exit [duplicate]承诺和流量控制:提前退出[重复]
【发布时间】: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


【解决方案1】:

这是一个更完整的答案,不可能返回给调用者。因为 Promise 是异步运行的……换句话说,当 Promise 开始工作时,调用者已经返回。所以返回调用者是不可能的,因为调用者已经离开了。

如果你想离开promise,你可以简单地调用this.reject()你可以带一个参数reject。它将陷入catch 承诺中。如果您不想再处理then,也可以从catch 子句中reject。然后在某些时候,这将导致 promise 失败。

它可能不会完全符合您的要求,因为您至少必须处理最终的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)

这里有更多关于 Promise 的文档:http://promisejs.org/ 这是一本好书。

我希望你明白usingreject 很像试图通过引发异常来提前退出几个堆叠函数的函数。我不鼓励这样做,因为它可能非常糟糕且难以理解其背后的逻辑。如果您必须提前退出承诺,即使没有异常或错误,那么您可能需要重新考虑您的流程。

你可以这样做:

outerFunction = ->
  Q()
    .then ->
      doSomethingAsync
    .then (result) ->

      if return_now
         return result if result is someSpecialValue
      return Q()
         .then ->
           ...
         .then ->
           ...
         .then ->
           ...

您可以返回结果或返回将继续流程链的承诺。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2017-12-14
  • 2019-06-13
  • 2023-02-17
  • 1970-01-01
  • 2019-11-09
  • 1970-01-01
  • 2016-03-09
  • 2019-07-18
相关资源
最近更新 更多