实现 arrange 函数
arrange('William').execute();
// > William is notified
arrange('William').do('commit').execute();
// > William is notified
// > Start to commit
arrange('William').wait(5).do('commit').execute();
// > William is notified
// 等待5秒
// > Start to commit
arrange('William').waitFirst(5).do('push').execute();
// 等待5秒
// > William is notified
// > Start to push
解答
function arrange(str) {
return new Arrange(str)
}
class Arrange {
constructor(str){
this.str = str
this.tasks = [] // 核心,使用队列(数组)来存储要执行的函数
this.tasks.push(() => console.log(`${this.str} is notified`))
}
async execute() {
for(const t of this.tasks) {
await t() // 执行队列中的函数
}
}
do(action) {
this.tasks.push(() => {
console.log(`start to ${action}`);
})
return this
}
wait(time) {
this.tasks.push(() => new Promise((resolve) => {
console.log(`等待 ${time} s`);
setTimeout(() => resolve(), time * 1000)
}))
return this
}
waitFirst(time) {
this.tasks.unshift(() => new Promise((resolve) => {
console.log(`等待 ${time} s`);
setTimeout(() => resolve(), time * 1000)
}))
return this
}
}
网友评论