Created
January 30, 2014 09:09
-
-
Save niusounds/8705023 to your computer and use it in GitHub Desktop.
Node.jsでの処理同期化いろいろ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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