La primera forma de escribir:
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 dinnerLa segunda forma de escribir:
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 2const fn = array.shift() fn && fn(); matriz.shift() && matriz.shift()();
Los resultados de salida de la consola del primer método y el segundo método son inconsistentes. El segundo método solo genera el resultado de "Despertar después de 2", que no es lo que quiero, quiero saber por qué.
shift modifica la matriz, reduciendo su longitud en 1 y devolviendo la cabeza de la matriz. Así que con tu primer código:
const fn = array.shift() fn && fn() Llamas shift una vez y asignas la primera función a fn . Verifica si fn existe y luego lo llama si existe. La matriz ahora tiene 1 entrada menos que antes.
Su código alternativo llama al turno 3 veces:
const fn = array.shift() array.shift() && array.shift()() El primer elemento de la matriz se asigna a fn y nunca se usa. El segundo elemento de la matriz determina si ejecutar &&, y el tercer elemento de la matriz es el que se llama (o lanza una excepción si no existe).