-
-
Notifications
You must be signed in to change notification settings - Fork 235
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
有并发限制的Promise.all(ts类型) #147
Comments
class Run {
tasks = [];
flag = 0;
constructor(tasks, num) {
this.tasks = tasks;
this.num = num;
this.flag = 0;
}
run() {
if (!this.num) return;
new Array(this.num).fill(0).forEach(this.runOne.bind(this));
}
async runOne() {
if (!this.tasks.length) return;
if (this.flag >= this.num) return;
const task = this.tasks.shift();
this.flag++;
await task();
if (this.flag > 0) this.flag--;
await this.runOne();
}
}
const sleep = (duration) =>
new Promise((resolve) =>
setTimeout(() => {
console.log("task " + duration + " done");
resolve();
}, duration)
);
const tasks = new Array(10).fill(() => sleep(1000 + Math.random() * 3000));
const run = new Run(tasks, 2);
run.run(); |
测试代码: function sleep(text, delay = 1000) {
return () => new Promise(resolve => {
setTimeout(() => {
console.log(text)
resolve();
}, delay);
});
}
const tasks = [1, 2, 3, 4, 5].map((i) => {
return sleep(i)
}) 测试代码: 预期结果:
方案一: 基于
|
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
No description provided.
The text was updated successfully, but these errors were encountered: