用Promise實現:帶延時功能的鏈式調用

 

 

 1 // 1) 調用方式
 2 new People('whr').sleep(3).eat('apple').sleep(5).eat('durian');
 3 
 4 // 2) 打印結果
 5 'hello, whr' -(等待3s)--> 'whr eat apple' -(等待5s)--> 'whr eat durian'
 6 
 7 // 3) 以下是代碼實現
 8 class People {
 9   constructor(name) {
10     this.name = name;
11     this.sayHello();
12     this.queue = Promise.resolve();
13   }
14   sayHello() {
15     console.log(`hello, ${this.name}`);
16   }
17   sleep(time) {
18     this.queue = this.queue.then(() => {
19       return new Promise(res => {
20         setTimeout(() => {
21           res();
22         }, time * 1000)
23       })
24     })
25     return this;
26   }
27   eat(food) {
28     this.queue = this.queue.then(() => {
29       console.log(`${this.name} eat ${food}`);
30     })
31     return this;
32   }
33 }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章