0
我必须执行多个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]
它按预期的方式工作,或多或少。当有多个承诺时,then
处理程序$.when
将获得一个数组数组(例如,Chrome浏览器控制台中显示的[[Object, "success", Object], [Object, "success", Object]]
)。 _.each
然后可以正确解压到result, idx
。
但是,如果只有1个承诺,我将只在then
处理程序中获得单个数组。它混淆了_.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
支票?