用Promise实现一个支持异步执行的队列
题目:实现一个 Queue 类,支持按顺序执行异步队列,push 方法把一个待执行函数推入队列,run 函数开始运行队列
Queue.push(function(){
return new Promise((resolve,reject)=>{
setTimeout(()=>{
console.log('1');
resolve()
},1000)
})
}).push(function(){
console.log('2')
}).push(function(){
return new Promise((resolve,reject)=>{
setTimeout(()=>{
console.log('3');
resolve()
},500)
})
})
上述代码输出需为 1,2,3
实现如下
class Queue{
constructor(){
this.stack = []
}
push(fn){
this.stack.push(fn)
return this
}
run(){
var sequence = Promise.resolve()
this.stack.forEach(item=>{
sequence = sequence.then(item)
})
}
}
var q = new Queue()
q.push(function(){
return new Promise((resolve)=>{
setTimeout(()=>{
console.log('1');
resolve()
},1000)
})
}).push(function(){
console.log('2');
}).push(function(){
return new Promise((resolve)=>{
setTimeout(()=>{
console.log('3');
resolve()
},500)
})
}).run()