promise concurrency

基于promise 并发控制

Ten skrypt nie powinien być instalowany bezpośrednio. Jest to biblioteka dla innych skyptów do włączenia dyrektywą meta // @require https://update.greasyfork.org/scripts/488850/1336774/promise%20concurrency.js

Aby zainstalować ten skrypt, wymagana jest instalacje jednego z następujących rozszerzeń: Tampermonkey, Greasemonkey lub Violentmonkey.

Aby zainstalować ten skrypt, wymagana jest instalacje jednego z następujących rozszerzeń: Tampermonkey, Violentmonkey.

Aby zainstalować ten skrypt, wymagana jest instalacje jednego z następujących rozszerzeń: Tampermonkey, Violentmonkey.

Aby zainstalować ten skrypt, wymagana będzie instalacja rozszerzenia Tampermonkey lub Userscripts.

You will need to install an extension such as Tampermonkey to install this script.

Aby zainstalować ten skrypt, musisz zainstalować rozszerzenie menedżera skryptów użytkownika.

(Mam już menedżera skryptów użytkownika, pozwól mi to zainstalować!)

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

Będziesz musiał zainstalować rozszerzenie menedżera stylów użytkownika, aby zainstalować ten styl.

Będziesz musiał zainstalować rozszerzenie menedżera stylów użytkownika, aby zainstalować ten styl.

Musisz zainstalować rozszerzenie menedżera stylów użytkownika, aby zainstalować ten styl.

(Mam już menedżera stylów użytkownika, pozwól mi to zainstalować!)

// ==/UserScript==
// @version               1.0
// ==/UserScript==

; (() => {
  /**
   * # 使用方法
   * ```js
   * await concurrentTasks(5, [1, 2, 3, 4], (n) => {
   *   return new Promise((ok) => {
   *     setTimeout(() => {
   *       console.log(n);
   *       ok();
   *     }, Math.random() * 5000);
   *   });
   * });
   * ```
   * @template T
   * @param {number} limit - 并发数
   * @param {T[] | NodeListOf<T>} tasks - 可迭代对象
   * @param {(task:T) => Promise<void>} asyncCallback - Promise 回调函数
   * @returns {Promise<void>}
   */
  const concurrentTasks = async (limit, tasks, asyncCallback) => {
    limit = Math.min(limit, tasks.length);
    let index = 0;
    const run = async () => {
      while (index < tasks.length) {
        await asyncCallback(tasks[index++]);
      }
    };
    const runTaks = Array.from({ length: limit }, () => run());
    await Promise.all(runTaks);
  };

  window.concurrentTasks = concurrentTasks;
})();