题目要求:实现一个Queue类,要求调用task可以实现定时任务。比如Queue().task(1, 1000)是一秒输出数字,Queue().task(2, 2000)两秒之后输出数字2,Queue().task(3, 3000)3秒之后输出3。当调用run()方法之后再开始执行输出。
思路:题意要求类中有两个方法,并且调用run之后才能执行,那么想到用promise或者async/await去实现这个功能。
先用promise实现
function Queue(){
this.task = (num, time) => {
return new Promise((resolve, reject) => {
setTimeout(()=> {
console.log(num)
resolve(num);
}, time);
})
};
this.run = () => {
//并行
let first = this.task(1, 1000);
let second= this.task(2, 2000);
let third= this.task(3, 3000);
Promise.all([first, second, third]).then((result) => {
console.log(result);
});
//串行
this.task(1, 1000).then((result) => {
this.task(2, 2000).then((result) => {
this.task(3, 3000);
});
});
}
}
let queue = new Queue();
queue.run();
接下来用async/await关键字实现
function Queue(){
this.task = (num, time) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(num);
resolve(num);
}, time);
})
};
this.run = async () => {
//串行
let first = await this.task(1, 1000);
let second = await this.task(2, 3000);
let third = await this.task(3, 3000);
console.log(first, second, third);
//并行
let task = [];
for(let i = 1; i < 4; i ++){
task.push(this.task(i, i * 1000));
};
Promise.all(task);
};
}
let queue = new Queue();
queue.run();