Skip to content

Instantly share code, notes, and snippets.

@niusounds
Created January 30, 2014 09:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save niusounds/8705023 to your computer and use it in GitHub Desktop.
Save niusounds/8705023 to your computer and use it in GitHub Desktop.
Node.jsでの処理同期化いろいろ
function each(arr, iterator, onEnd) {
var endIdx = arr.length - 1;
arr.forEach(function(i, idx) {
iterator.apply(this, [i, idx,
function() {
if (idx === endIdx) {
if ( typeof onEnd === 'function') {
setImmediate(onEnd);
}
}
}]);
});
}
function serial(arr, iterator, onEnd) {
var endIdx = arr.length - 1;
if (endIdx < 0) {
onEnd();
return;
}
setImmediate(loop, 0);
function loop(idx) {
setImmediate(iterator, arr[idx], idx, function() {
if (idx === endIdx) {
if ( typeof onEnd === 'function') {
setImmediate(onEnd);
}
} else {
setImmediate(loop, idx + 1);
}
});
}
}
function synchronized(funcs, onEnd) {
serial(funcs, function(func, idx, next) {
setImmediate(func, idx, next);
}, onEnd);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment