async.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. var eachLimit = function (arr, limit, iterator, callback) {
  2. callback = callback || function () {};
  3. if (!arr.length || limit <= 0) {
  4. return callback();
  5. }
  6. var completed = 0;
  7. var started = 0;
  8. var running = 0;
  9. (function replenish () {
  10. if (completed >= arr.length) {
  11. return callback();
  12. }
  13. while (running < limit && started < arr.length) {
  14. started += 1;
  15. running += 1;
  16. iterator(arr[started - 1], function (err) {
  17. if (err) {
  18. callback(err);
  19. callback = function () {};
  20. } else {
  21. completed += 1;
  22. running -= 1;
  23. if (completed >= arr.length) {
  24. callback();
  25. } else {
  26. replenish();
  27. }
  28. }
  29. });
  30. }
  31. })();
  32. };
  33. var retry = function (times, iterator, callback) {
  34. var next = function (index) {
  35. iterator(function (err, data) {
  36. if (err && index < times) {
  37. next(index + 1);
  38. } else {
  39. callback(err, data);
  40. }
  41. });
  42. };
  43. if (times < 1) {
  44. callback();
  45. } else {
  46. next(1);
  47. }
  48. };
  49. var async = {
  50. eachLimit: eachLimit,
  51. retry: retry
  52. };
  53. module.exports = async;