많은 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]
예상대로 작동합니다. 약속이 2 개 이상인 경우 핸들러는 $.when
이며 배열은 배열로 표시됩니다 (예 : Chrome 개발자 콘솔에 표시되는 [[Object, "success", Object], [Object, "success", Object]]
). _.each
은 result, idx
으로 정확하게 포장을 풉니 다.
그러나 약속이 하나만있는 경우 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
수표로 삭제할 수 있나요?