一个class运用promise的延时调用

使用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
复制代码

转载于:https://juejin.im/post/5d030a4f51882544d33ba371

你可能感兴趣的:(一个class运用promise的延时调用)