【发布时间】:2016-10-07 01:59:10
【问题描述】:
我必须执行一些 json 调用并对结果应用回调。调用次数在运行前是未知的。因此,我使用$.when.apply 将一组承诺传递给when。
jsonPromises = []
newContentActions = []
for model in models
jsonPromises.push contentCreator.create(model)
action = new ActionHandler model
newContentActions.push action
$.when.apply($, jsonPromises)
.then (args...) =>
_.each args, (result, idx) =>
return unless result[1] is 'success'
action = newContentActions[idx]
action result[0]
它或多或少地按预期工作。当有多个承诺时,$.when 的 then 处理程序将获得一个数组数组(例如,在 Chrome 开发控制台中看到的[[Object, "success", Object], [Object, "success", Object]])。然后_.each 可以正确解压到result, idx。
但是,如果只有 1 个承诺,我只会在 thenhandler 中获得一个数组。它混淆了_.each。 each 解包单个数组并生成 3 个函数调用。我的应用程序失败了。
为了解决这个问题,我对承诺的数量进行了额外检查。只有一个的时候我不会用$.when:
if jsonPromises.length is 1
jsonPromises[0].done (model) =>
action = newContentActions[0]
action model
else
$.when.apply($, jsonPromises)
.then (args...) =>
_.each args, (result, idx) =>
return unless result[1] is 'success'
action = newContentActions[idx]
action result[0]
这是实现此结果的唯一方法吗?有没有办法去掉
jsonPromises.length is 1检查?
【问题讨论】:
标签: jquery coffeescript underscore.js