抱歉,您的浏览器无法访问本站

本页面需要浏览器支持(启用)JavaScript


了解详情 >

需要顺序执行的任务太多了怎么办?写个异步队列吧!

代码实现

// async-queue.ts
export default class AsyncQueue {
    private running: Boolean;
    private queue: Array<() => Promise<any>>;

    constructor() {
        this.running = false;
        this.queue = [];
    }

    public push(Fn: Function): void {
        setTimeout(() => {
            this.queue.push(async () => {
                this.running = true
                await Fn();
                this.running = false
                this.queue.shift()?.();
            });

            if (!this.running) {
                this.queue.shift()?.();
            }
        })
    }
}

测试:


// index.ts
import AsyncQueue from "./async-queue";

const sleep = (t: number) => new Promise(resolve => setTimeout(resolve, t))

const queue = new AsyncQueue();

queue.push(async () => {
    await sleep(1000)
    console.log(new Date().toLocaleTimeString())
})

queue.push(async () => {
    await sleep(1000)
    console.log(new Date().toLocaleTimeString())
})

queue.push(async () => {
    await sleep(1000)
    console.log(new Date().toLocaleTimeString())
})

queue.push(async () => {
    await sleep(1000)
    console.log(new Date().toLocaleTimeString())
})

queue.push(async () => {
    await sleep(1000)
    console.log(new Date().toLocaleTimeString())
})

效果

下午5:02:42
下午5:02:43
下午5:02:44
下午5:02:45
下午5:02:46

来源

评论