1. function machine() {
    2. }
    3. machine('ygy').execute()
    4. // start ygy
    5. machine('ygy').do('eat').execute();
    6. // start ygy
    7. // ygy eat
    8. machine('ygy').wait(5).do('eat').execute();
    9. // start ygy
    10. // wait 5s(这里等待了5s)
    11. // ygy eat
    12. machine('ygy').waitFirst(5).do('eat').execute();
    13. // wait 5s
    14. // start ygy
    15. // ygy eat
    1. function machine(name){
    2. return new Machine(name);
    3. }
    4. function Machine(name){
    5. this.name = name;
    6. this.actions = [];
    7. this.init();
    8. }
    9. Machine.prototype.init = function(){
    10. this.actions.push(`start ${this.name}`)
    11. }
    12. Machine.prototype.wait = function(seconds){
    13. this.actions.push(function(){
    14. return new Promise((resolve) => {
    15. console.log(`wait ${seconds}s`)
    16. setTimeout(()=>{resolve(seconds)},seconds*1000)
    17. })
    18. })
    19. return this
    20. }
    21. Machine.prototype.waitFirst = function(seconds){
    22. this.actions.unshift(function(){
    23. return new Promise((resolve) => {
    24. console.log(`wait ${seconds}s`)
    25. setTimeout(()=>{resolve(seconds)},seconds*1000)
    26. })
    27. })
    28. return this
    29. }
    30. Machine.prototype.do = function(action){
    31. this.actions.push(`${this.name} ${action}`)
    32. return this
    33. }
    34. Machine.prototype.execute = async function(){
    35. for(let i in this.actions){
    36. if(typeof this.actions[i] === 'function'){
    37. await this.actions[i]()
    38. }else {
    39. console.log(this.actions[i])
    40. }
    41. }
    42. }