js promise 实现异步队列

使用

import {Queue} from "@/promiseQueue"
const queue = new Queue()
queue.enqueue((resolve,reject) => {
    try {
        // do something
        resolve(result)
    } catch (err) {
		reject(err)
    }
}).then(result=>{
	console.log('success')
}).catch(err=>{
	console.error(err)
})

promiseQueue模块源码

export function Queue() {
    this.queue = []
    this.flushing = false
    this.enqueue = function (executor) {
        const p = new Promise((resolve, reject) => {
            this.queue.push(new Task(executor, resolve, reject))
        })
        if (!this.flushing) {
            this.flushing = true
            chain()
        }
        return p
    }

    const chain = () => {
        const nextTask = this.queue.shift()
        if (nextTask) {
            return nextTask.execute().then(() => {
                chain()
            })
        } else {
            this.flushing = false
        }
    }
}

function Task(executor, resolve, reject) {
    this.execute = () => {
        return new Promise(executor).then(resolve).catch(reject)
    }
}

posted on 2022-04-11 22:37  路过君  阅读(21)  评论(0编辑  收藏  举报

导航