Skip to content

asyncThrottle 异步并发节流 #46

@varHarrie

Description

@varHarrie
function asyncThrottle(tasks: Array<() => Promise<unknown>>, concurrency = 1) {
  return new Promise<void>((resolve) => {
    const entries = tasks.entries();
    let remains = tasks.length;

    const run = () => {
      const { value } = entries.next();
      if (!value) return;

      const [, task] = value;
      task().finally(() => {
        remains -= 1;
        return remains ? run() : resolve();
      });
    };


    Array.from({ length: concurrency }).forEach(run);
  });
}

// Example:

function delay() {
  const ms = Math.floor(Math.random() * 3000);
  const bool = Math.random() > 0.5 
  return new Promise((resolve, reject) => setTimeout(bool ? resolve : reject, ms));
}

const tasks = Array
  .from({ length: 10 })
  .map((_, i) => () => delay().then(() => console.log(i)));

asyncThrottle(tasks, 2);

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions