链接jQuery承诺通过回调

时间:2014-06-12 17:25:51

标签: jquery callback coffeescript promise jquery-deferred

我发现自己发明了一个使用jQuery承诺的模式,并且想知道它是否已经存在于其他地方。

基本上,我有一系列异步操作需要一个接一个地发生 - 但它们不一定都是相同的动作,动作可能是有条件的。

它可能看起来像这样(CoffeeScript语法简洁):

a = itemA.save()
a.done ->
  b = itemB.fetch()
  b.done ->
    if x
      c = itemC.fetch()
      c.done ->
        ui.showDone()
    else
      ui.showDone()

请注意丑陋:

  • 过度嵌套
  • 重复代码

我的作文程序减少了嵌套。在使用中,它看起来像这样:

chain = itemA.save()
chain = andThen chain, ->
  itemB.fetch()
chain = andThen chain, ->
  if x
    itemC.fetch()
chain.always ->
  ui.showDone()

andThen看起来像这样:

andThen = (promise, doneCallback) ->
  result = $.Deferred()
  promise.fail (value) ->
    result.reject(value)
  promise.done (value) ->
    cbResult = doneCallback(value)
    if cbResult && cbResult['done']
      cbResult.done (value) ->
        result.resolve(value)
      cbResult.fail (value) ->
        result.reject(value)
    else
      result.resolve(cbResult)
  result.promise()

我可能正在重新发明轮子。但我还没有在其他任何地方找到这个轮子。它在哪里?

我主要使用promises来抽象显示错误消息,在请求飞行时禁用按钮等等。而不是使用promises嵌入这些内容,我可以放弃对能够对正在进行的行动的成功或失败做出反应的组件的承诺。它使UI更加一致和可组合。

这意味着我需要一个代表多个延期链的整个链的承诺 - 无论采取何种路径,都将得到解决。

1 个答案:

答案 0 :(得分:1)

  

我可能正在重新发明轮子。但我还没有找到这个轮子。它在哪里?

它甚至有一个类似的名称:.then()方法!它实际上是main ideapromises

itemA.save().then ->
  itemB.fetch()
.then ->
  if x
    itemC.fetch()
.always ->
  ui.showDone()
相关问题