Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

asyncThrottle 异步并发节流 #46

Open
varHarrie opened this issue Jun 10, 2022 · 0 comments
Open

asyncThrottle 异步并发节流 #46

varHarrie opened this issue Jun 10, 2022 · 0 comments
Milestone

Comments

@varHarrie
Copy link
Owner

varHarrie commented Jun 10, 2022

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);
@varHarrie varHarrie added this to the Snippets milestone Jun 10, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant