Skip to content
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

Q37. JS实现一个带并发限制的异步调度器Scheduler #37

Open
lstoryc opened this issue Oct 21, 2020 · 0 comments
Open

Q37. JS实现一个带并发限制的异步调度器Scheduler #37

lstoryc opened this issue Oct 21, 2020 · 0 comments

Comments

@lstoryc
Copy link
Owner

lstoryc commented Oct 21, 2020

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(() => {
		  		this.run.splice(this.run.indexOf(promise), 1)
		  	})
		  	this.run.push(promise)
		  	return promise
		} else {
		  	return Promise.race(this.run).then(() => this.schedule())
		}
	}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant