设计含有异步队列执行任务的class

153 阅读1分钟

实现效果

LazyMan('Tony').sleep(10).eat('lunch').eat('dinner')

  • "Hi I am Tony"
  • "等待了10秒..."
  • "iam eating lunch"
  • "iam eating dinner"
  • class LazyManClass{
      constructor(name){
        this.name=name;
        this.queue=[];
        console.log(`Hi I am ${name}`); 
        setTimeout(()=>{
          this.next();
        },0)
      }
      
      sleep(time){
        const fn=()=>{
          setTimeout(()=>{
             console.log(`等待了${time}秒...`)
              this.next()
           },time*1000)
       }   
         this.queue.unshift(fn);
        return this
       }
      
      eat(food){
          const fn=()=>{
           console.log(`iam eating ${food}`)
            this.next()
           }
          this.queue.push(fn)
          return this 
        }
       
      next(){
        const fn=this.queue.shift();
        fn && fn();
        }
         
     
    }
    const LazyMan=(name)=>{ 
      return new LazyManClass(name)
    };
    LazyMan('Tony').sleep(10).eat('lunch').eat('dinner')