javascript - promise 和流量控制 : Early exit

标签 javascript coffeescript q

<分区>

我最近开始用 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 -> 
      ...

最佳答案

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

如果你想离开 promise ,你可以简单地调用this.reject()您可以使用参数拒绝。它会陷入 catch promise 。你可以reject来自catch如果您不想再处理它,也可以使用子句then .然后在某个时候,这将导致 promise 失败。

它可能不会完全按照您的要求进行,因为您至少必须处理最终的 catch处理错误或为什么你提前离开 promise 。但即使是 catch是一个 promise 。

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/这是一本好书。

我希望你明白using reject 非常类似于通过引发异常来尝试提前退出堆栈函数对。我不鼓励这样做,因为它可能非常糟糕并且很难理解其背后的逻辑。如果即使没有异常或错误也必须提前退出 promise ,那么您可能需要重新考虑您的流程。

你可以做的是:

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

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

您可以返回结果或返回将继续处理链的 promise 。

关于javascript - promise 和流量控制 : Early exit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35098110/

相关文章:

ruby-on-rails - 使用:coffescript filter inside HAML templates?对性能的影响

javascript - 单击事件上的 CoffeeScript 不起作用

Javascript:如何使用 promise 迭代数组?

javascript - 相当于 jQuery :contains() selector 的 native javascript

javascript - 不确定这段 JS 代码在做什么

javascript - undefined 不是一个函数(评估 x.json())

javascript - 为什么 CoffeeScript 以这种方式编译单个参数函数?

javascript - WebStorm - 调试器在断点处终止进程。进程完成,退出代码为 -1073741510

javascript - 确定 promise 需要多长时间

javascript - AngularJS:避免在收到响应之前两次调用相同的 REST 服务