promise concurrency

基于promise 并发控制

This script should not be not be installed directly. It is a library for other scripts to include with the meta directive // @require https://update.greatest.deepsurf.us/scripts/488850/1336774/promise%20concurrency.js

  1. // ==/UserScript==
  2. // @version 1.0
  3. // ==/UserScript==
  4.  
  5. ; (() => {
  6. /**
  7. * # 使用方法
  8. * ```js
  9. * await concurrentTasks(5, [1, 2, 3, 4], (n) => {
  10. * return new Promise((ok) => {
  11. * setTimeout(() => {
  12. * console.log(n);
  13. * ok();
  14. * }, Math.random() * 5000);
  15. * });
  16. * });
  17. * ```
  18. * @template T
  19. * @param {number} limit - 并发数
  20. * @param {T[] | NodeListOf<T>} tasks - 可迭代对象
  21. * @param {(task:T) => Promise<void>} asyncCallback - Promise 回调函数
  22. * @returns {Promise<void>}
  23. */
  24. const concurrentTasks = async (limit, tasks, asyncCallback) => {
  25. limit = Math.min(limit, tasks.length);
  26. let index = 0;
  27. const run = async () => {
  28. while (index < tasks.length) {
  29. await asyncCallback(tasks[index++]);
  30. }
  31. };
  32. const runTaks = Array.from({ length: limit }, () => run());
  33. await Promise.all(runTaks);
  34. };
  35.  
  36. window.concurrentTasks = concurrentTasks;
  37. })();