给定每个触发异步事件的操作列表,如何以保证的顺序执行所有操作:
$.each(actions, function(i, action) {
action.execute(); // triggers an asynch process;
// how do I ensure that the next action isn't triggered until the current completes?
});
我有一个想法是让每个异步执行的完成触发一个自定义事件,但我不确定如何构造逻辑,因为需要在循环中为列表中的每个动作触发这些:
$.each(actions, function(i, action) {
action.on('executed', function() {
// continue on to next action; but how to structure this?
// In other words, how to sequentially chain a non-fixed # of callbacks?
});
action.execute();
});
答案 0 :(得分:0)
有了这个:
(function execAction(i){
if( i >= actions.length) return; //When all has finished, do nothing
actions[i].execute(function(yourCallbackParams){
execAction(i+1);
});
})(0); //Start with i == 0
假设.execute
收到回调作为参数
干杯