function machine() {
}
machine('ygy').execute()
// start ygy
machine('ygy').do('eat').execute();
// start ygy
// ygy eat
machine('ygy').wait(5).do('eat').execute();
// start ygy
// wait 5s(这里等待了5s)
// ygy eat
machine('ygy').waitFirst(5).do('eat').execute();
// wait 5s
// start ygy
// ygy eat
function machine(name){
return new Machine(name);
}
function Machine(name){
this.name = name;
this.actions = [];
this.init();
}
Machine.prototype.init = function(){
this.actions.push(`start ${this.name}`)
}
Machine.prototype.wait = function(seconds){
this.actions.push(function(){
return new Promise((resolve) => {
console.log(`wait ${seconds}s`)
setTimeout(()=>{resolve(seconds)},seconds*1000)
})
})
return this
}
Machine.prototype.waitFirst = function(seconds){
this.actions.unshift(function(){
return new Promise((resolve) => {
console.log(`wait ${seconds}s`)
setTimeout(()=>{resolve(seconds)},seconds*1000)
})
})
return this
}
Machine.prototype.do = function(action){
this.actions.push(`${this.name} ${action}`)
return this
}
Machine.prototype.execute = async function(){
for(let i in this.actions){
if(typeof this.actions[i] === 'function'){
await this.actions[i]()
}else {
console.log(this.actions[i])
}
}
}