美文网首页
2020-07-20 Promise编程:Scheduler

2020-07-20 Promise编程:Scheduler

作者: 苦庭 | 来源:发表于2020-07-20 06:19 被阅读0次
  1. 一个讲promise-problem讲得很好的blog
  2. 一个解释了Promise静态方法的用法的gist
class Scheduler {
    constructor(count) {
        this.count = 2
        this.queue = []
        this.run = []
    }

    add(task) {
        this.queue.push(task)
        return this.schedule()
    }

    schedule() {
        if (this.run.length < this.count && this.queue.length) {
            const task = this.queue.shift()
            const promise = task().then(() => { // promise 中定义了任务完成后在run数组中删除当前promise
                this.run.splice(this.run.indexOf(promise), 1)
            })
            this.run.push(promise)
            return promise
        } else {
            return Promise.race(this.run).then(() => this.schedule())
        }
    }
}

const timeout = (time) => new Promise(resolve => {
    setTimeout(resolve, time)
})

const scheduler = new Scheduler()
const addTask = (time, order) => {
    scheduler.add(() => timeout(time)).then(() => console.log(order))
}

addTask(1000, '1')
addTask(500, '2')
addTask(300, '3')
addTask(400, '4')
// output: 2 3 1 4

相关文章

网友评论

      本文标题:2020-07-20 Promise编程:Scheduler

      本文链接:https://www.haomeiwen.com/subject/vmnskktx.html