如何使 _.each 在 $.when done 处理程序中同时处理 'array' 和 'array of array'
How to make _.each handle both 'array' and 'array of array' in $.when done handler
我必须执行多次 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]
它或多或少按预期工作。当有超过 1 个承诺时,$.when
的 then
处理程序将获得一个数组数组(例如 Chrome 开发控制台中看到的 [[Object, "success", Object], [Object, "success", Object]]
)。 _.each
然后可以正确解压成 result, idx
.
但是,如果只有 1 个承诺,我只会在 then
处理程序中获得一个数组。它混淆了 _.each
。 each
将单个数组解压缩并生成 3 个函数调用。我的应用程序失败了。
为了解决这个问题,我额外检查了 promise 的数量。只有一个的时候我不会用$.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
检查?
如果您看到 jsonPromises.length
是 1
,我的解决方案是将 args 包装在一个数组中
$.when.apply($, jsonPromises)
.then (args...) =>
args = [args] if jsonPromises.length is 1
_.each args, (result, idx) =>
return unless result[1] is 'success'
action = newContentActions[idx]
action result[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]
它或多或少按预期工作。当有超过 1 个承诺时,$.when
的 then
处理程序将获得一个数组数组(例如 Chrome 开发控制台中看到的 [[Object, "success", Object], [Object, "success", Object]]
)。 _.each
然后可以正确解压成 result, idx
.
但是,如果只有 1 个承诺,我只会在 then
处理程序中获得一个数组。它混淆了 _.each
。 each
将单个数组解压缩并生成 3 个函数调用。我的应用程序失败了。
为了解决这个问题,我额外检查了 promise 的数量。只有一个的时候我不会用$.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
检查?
如果您看到 jsonPromises.length
是 1
$.when.apply($, jsonPromises)
.then (args...) =>
args = [args] if jsonPromises.length is 1
_.each args, (result, idx) =>
return unless result[1] is 'success'
action = newContentActions[idx]
action result[0]