zoukankan      html  css  js  c++  java
  • 用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 }
  • 相关阅读:
    ORACLE表空间管理维护
    oracle表分区详解
    Jquery
    B
    A
    E
    字符串排成字典序,字符串数组
    命令,快捷键,配置
    第一个java程序
    A
  • 原文地址:https://www.cnblogs.com/ronffy/p/8919468.html
Copyright © 2011-2022 走看看