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