const lazyMan =function(aa) {
? let arr = []
? arr.push(()=>{
? ? console.log(' I‘a(chǎn)m '+aa)
? ? next()
? })
? const next = ()=>{
? ? let fn = arr.shift()
? ? if(fn) fn()
? }
? const api = {
? ? sleep(timer){
? ? ? arr.push(()=>{
? ? ? ? setTimeout(()=>{
? ? ? ? ? console.log(' sleep '+timer+'s ')
? ? ? ? ? next()
? ? ? ? },timer*1000)
? ? ? })
? ? ? return api
? ? },
? ? eat(food){
? ? ? arr.push(()=>{
? ? ? ? ? console.log(' eat '+food)
? ? ? ? ? next()
? ? ? })
? ? ? return api
? ? },
? ? sleepFirst(timer){
? ? ? arr.unshift(()=>{
? ? ? ? setTimeout(()=>{
? ? ? ? ? console.log(' sleepfirst '+timer+' s ')
? ? ? ? ? next()
? ? ? ? },timer*1000)
? ? ? })
? ? ? return api
? ? },
? }
? setTimeout(next)
? return api
}
然后說一下我的思路吧慈省,lazyMan這個(gè)對(duì)象可以無限次調(diào)用痹束,那么肯定返回的是個(gè)對(duì)象滑黔,而且對(duì)象中的方法返回的還是這個(gè)對(duì)象策泣。
所以就有了?
const lazyMan = {
const api = {
sleep:()=>{
...
return api
},
...
}
return api
}
然后鏈?zhǔn)秸{(diào)用時(shí)后面的要等前面的先執(zhí)行
所以需要一個(gè)隊(duì)列微饥,在隊(duì)列中執(zhí)行一個(gè),再調(diào)用下一個(gè)
就需要?let arr = []和??
const next = ()=>{
? ? let fn = arr.shift()
? ? if(fn) fn()
? }
sleep:(timer)=>{
setTimeout(()=>{
? ? ...
? ? next()
},timer)
return api
},
然后就是最重要的
在lazyMan內(nèi)部 一定要使用setTimeout(next)去進(jìn)行第一次的調(diào)用
因?yàn)?lazyMan('peter').sleep(2).sleepFirst(5).eat('shit') 代碼是同步執(zhí)行的
如果直接調(diào)用next 那么此時(shí)隊(duì)列中沒有其他函數(shù),所以需要同步代碼執(zhí)行完畢后才開始執(zhí)行next方法