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

JavaScript实现一个简单队列,顺序执行异步任务 #3

Open
54leibo opened this issue Jul 3, 2019 · 0 comments
Open

JavaScript实现一个简单队列,顺序执行异步任务 #3

54leibo opened this issue Jul 3, 2019 · 0 comments

Comments

@54leibo
Copy link
Owner

54leibo commented Jul 3, 2019

功能描述

  • QueueJob构造函数实例存在一个queue方法,该方法接收一个Promise;能够保证按照调用的顺序依次执行传入的callback,即使其中包含异步代码
class QueueJob {
  queue(callback) {
     const previous = this.pending || Promise.resolve()
     this.pending = previous.then(callback).catch(callback)
     // 利用闭包保存当前pending
     const current = this.pending
     current.then(() => {
             // this.pending 完成时,this.pending没有被覆盖
            if(this.pending === current) {
                delete this.pending
            }
      })
  }
}

var queueJob = new QueueJob()

queueJob.queue(() => {
	return new Promise((resolve, reject) => {
		setTimeout(() => {
			console.log('first')
			resolve()
		}, 2000)
	})
})

queueJob.queue(() => {
	return new Promise((resolve, reject) => {
		setTimeout(() => {
			console.log('second')
			resolve()
		}, 1000)
	})
})

queueJob.queue(() => {
	return new Promise((resolve, reject) => {
		setTimeout(() => {
			console.log('three')
			resolve()
		}, 500)
	})
})

// first
// second
// three

扩展

@54leibo 54leibo changed the title javascritp实现一个简单队列,顺序执行异步任务 JavaScript实现一个简单队列,顺序执行异步任务 Jul 3, 2019
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