Skip to content

Instantly share code, notes, and snippets.

@kg8gk
Last active December 27, 2015 16:29
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 kg8gk/7355295 to your computer and use it in GitHub Desktop.
Save kg8gk/7355295 to your computer and use it in GitHub Desktop.
_eachLimit
var eachLimitFive = _eachLimit(5),
anArray = (function() {
var arr = [];
for (var i = 1; i <= 10; i++) {
arr.push(i);
}
return arr;
})();
// This is the iterator function
var asyncFn = function(data, callback) {
seTimeout(
function() {
console.log(data); // I/O operations, etc.
}, 0);
callback(); // Executed in JavaScript VM
};
}, onComplete = function(err) {
if (err) {
throw new Error("Error");
}
console.log("Complete");
};
/**
*
* I thought altough asyncFn hava asynchronous operations(aysnc function), when the code execucted to the line of 16,
* the callback executions for all of the 10 elements would be pushed in to a queue,
* like the multiple event handles in the browser, only one handle can be invoked at a time,
* and until the handle is finished, other handle can not be invoked.
* [
* callback call, // element 1, line 14
* callback call, // element 2
* callback call, // element 3
* ......
* ]
* Since only one callback call can be executed at a time(I think that they are exexcuted in the JavaScript VM)
* and _completed_ would be change only in the callback calls, and replenish() of the else clause also executed in JS vm,
* so I do not think
*/
eachLimitFive(anArray, asyncFn, onComplete);
/**
* Supposed that three asyncFn is executing, and one is in the asynchronous operations, and other two are going the execute
* the callback (line 16), and later __completed__ have been changed. Then another two replenish() calls. Since the
* __started__ have already reached the length of the array, it would not continue to executed. Now the excuting asyncFn
* called the callback, and it would go into the `else` clause and then `if (completed >= arr.length)` satisfied, and the
* onComplete callback would be executed.
* If the process above is right, another check that `completed` against `arr.length` is not necessary.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment