一個class運用promise的延時呼叫

嘻來樂發表於2019-06-14

使用prosmise鏈式呼叫可以實現延時呼叫的效果

class  Person {
  constructor(name){
     this.name = name;
     this.queue = Promise.resolve();
     this.sayHello();
  }
  sayHello(){
    console.log('say hello to:'+this.name);
    return this;
  }
  sleep(timer){
    this.queue = this.queue.then(() => {
      return new Promise(resolve=> {
        console.log('sleeping,wait:'+timer+'s')
        setTimeout(() => {
          resolve()
        },timer*1000)
      })
    })
    return this;
  }
  eat(fruit){
    this.queue = this.queue.then(() => {
      return new Promise(resolve => {
        console.log(this.name + ' like to eat' + fruit)
        resolve()
      })
    })
    return this;
  }
  
}
let o = new Person('bihuan');
o.sleep(3).eat('banana').sleep(5).eat('peach')
複製程式碼

執行結果,如下:

//say hello to:bihuan
//sleeping,wait:3s
//bihuan like to eatbanana
//sleeping,wait:5s
//bihuan like to eatpeach
複製程式碼

相關文章