Skip to content

Instantly share code, notes, and snippets.

@manxisuo
Created November 18, 2013 18:35
Show Gist options
  • Save manxisuo/7532926 to your computer and use it in GitHub Desktop.
Save manxisuo/7532926 to your computer and use it in GitHub Desktop.
顺序处理批量任务
/**
* @arr 待处理数组
* @handler 处理函数
*/
function handleBatch(arr, handler) {
// 参数校验
if (!arr || arr.length == 0 || !handler) return;
// 如果没有回调,则直接用循环;
// 否则,在处理完当前项后,在回调函数中处理下一个项。
if (handler.length == 1) {
arr.forEach(function(item) {
handler(item);
});
}
else if (handler.length == 2) {
var handleOne = function(start, arr, handler) {
handler(arr[start], function() {
if (start + 1 < arr.length) {
handleOne(start + 1, arr, handler);
}
});
};
handleOne(0, arr, handler);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment