一个class运用promise的延时调用
日期: 2019-06-14 分类: 个人收藏 316次阅读
使用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
除特别声明,本站所有文章均为原创,如需转载请以超级链接形式注明出处:SmartCat's Blog
标签:javascript
精华推荐