You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
classLazymanextendsPromise{eat(food){returnthis.then(function(){console.log(`eat ${food}`);});}sleep(time){returnthis.then(function(){returnnewLazyman((resolve,reject)=>{setTimeout(resolve,time);});});}}functionlazyman(name){console.log(`Hi, my name is ${name}`);returnLazyman.resolve();}lazyman('Maz').eat('lunch').sleep(3000).eat('dinner');
classLazymanextendsPromise{eat(food){returnthis.then(()=>{if(this.intro){returnthis.intro().then(()=>{this.intro=null;});}}).then(function(){console.log(`eat ${food}`);});}sleep(time){returnthis.then(function(){returnnewLazyman((resolve,reject)=>{setTimeout(resolve,time);});});}sleepFirst(time){returnthis.then(()=>{returnnewLazyman((resolve,reject)=>{setTimeout(()=>{this.intro().then(resolve)},time);});});}}functionlazyman(name){constman=Lazyman.resolve();man.intro=()=>newPromise((resolve,reject)=>{console.log(`Hi, my name is ${name}`);resolve();})returnman;}lazyman('Maz').sleepFirst(1000).eat('lunch').sleep(3000).eat('dinner');
这道题还没毕业的时候就看到过,这段时间突然又看到,联想到 promise,感觉还是很有意思
实现一个 LazyMan:
输出:
另外如果先调用了 sleepFirst 方法,要首先进行 sleep
输出:
The text was updated successfully, but these errors were encountered: