Skip to content

Commit

Permalink
如掉 async 模块引用
Browse files Browse the repository at this point in the history
  • Loading branch information
carsonxu committed Oct 31, 2017
1 parent 1ee895e commit 7f16e51
Showing 1 changed file with 56 additions and 0 deletions.
56 changes: 56 additions & 0 deletions lib/async.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
var eachLimit = function (arr, limit, iterator, callback) {
callback = callback || function () {};
if (!arr.length || limit <= 0) {
return callback();
}

var completed = 0;
var started = 0;
var running = 0;

(function replenish () {
if (completed >= arr.length) {
return callback();
}

while (running < limit && started < arr.length) {
started += 1;
running += 1;
iterator(arr[started - 1], function (err) {

if (err) {
callback(err);
callback = function () {};
} else {
completed += 1;
running -= 1;
if (completed >= arr.length) {
callback();
} else {
replenish();
}
}
});
}
})();
};

var retry = function (times, iterator, callback) {
var next = function (index) {
iterator(function (err, data) {
if (err && index < times) {
next(index + 1);
} else {
callback(err, data);
}
});
};
next(1);
};

var async = {
eachLimit: eachLimit,
retry: retry
};

module.exports = async;

0 comments on commit 7f16e51

Please sign in to comment.