The first way to write:
const LazyMan = function (name) {
const array = []
const fn = () => { console.log("Hi! This is " + name + '!'); next() }
const next = () => {
const fn = array.shift()
fn && fn()
// array.shift() && array.shift()()
}
array.push(fn)
setTimeout(() => { next() }, 0)
const api = {
sleep: (number) => {
array.push(() => {
setTimeout(() => { console.log('Wake up after ' + number); next() }, number * 1000)
})
return api
},
eat: (content) => {
array.push(() => {
console.log('eat ' + content); next()
})
return api
},
sleepFirst: (number) => {
array.unshift(() => {
setTimeout(() => { console.log('Wake up after ' + 5); next() }, number * 1000)
})
return api
}
}
return api
}
LazyMan("Hank").sleep(2).eat("dinner").sleepFirst(1);
// Wake up after 5
// Hi! This is Hank!
// Wake up after 2
// eat dinner
The second way to write:
const LazyMan = function (name) {
const array = []
const fn = () => { console.log("Hi! This is " + name + '!'); next() }
const next = () => {
const fn = array.shift()
// fn && fn()
array.shift() && array.shift()()
}
array.push(fn)
setTimeout(() => { next() }, 0)
const api = {
sleep: (number) => {
array.push(() => {
setTimeout(() => { console.log('Wake up after ' + number); next() }, number * 1000)
})
return api
},
eat: (content) => {
array.push(() => {
console.log('eat ' + content); next()
})
return api
},
sleepFirst: (number) => {
array.unshift(() => {
setTimeout(() => { console.log('Wake up after ' + number); next() }, number * 1000)
})
return api
}
}
return api
}
LazyMan("Hank").sleep(2).eat("dinner").sleepFirst(1);
// Wake up after 2
const fn = array.shift() fn && fn();
array.shift() && array.shift()();
The console output results of the first method and the second method are inconsistent, The second method only outputs the result of “Wake up after 2”, which is not what I want,I want to know why?