用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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM