Commit bc225c13 authored by nano's avatar nano

fix async

parent 5063725a
...@@ -64,20 +64,43 @@ export class Queue { ...@@ -64,20 +64,43 @@ export class Queue {
async run(task: Function) { async run(task: Function) {
this.queue.push(task); this.queue.push(task);
return await this.next(); await this.next();
} }
async next() { next() {
while (this.running < this.concurrency && this.queue.length) { return new Promise((res, rej) => {
let task: Function | undefined = this.queue.shift(); while (this.running < this.concurrency && this.queue.length) {
if (!task) { let task: Function | undefined = this.queue.shift();
return; if (!task) {
return rej();
}
this.running++;
return res(task(this, () => {
this.running--;
this.next();
}));
} }
this.running++; });
return await task(this, () => {
this.running--;
this.next();
});
}
} }
} }
const queue = new Queue({ concurrency: 1 });
async function main() {
let bundle = 1;
await queue.run(async (ctx, next) => {
bundle = await add(bundle);
next();
});
console.log(bundle);
}
async function add (number): Promise<number> {
await new Promise(resolve => setTimeout(() => resolve(number++), 5000));
return number;
}
main();
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment