Last active
October 21, 2021 08:14
-
-
Save sina42048/e934cdc1c430743c424506db3e7c779a to your computer and use it in GitHub Desktop.
behind the scene of async await loop
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const delay = (timeout) => new Promise((res, rej) => setTimeout(res, timeout)); | |
// (async function () { | |
// for (let i = 0; i < 10; i++) { | |
// console.log(i); | |
// await delay(2000); | |
// } | |
// })(); | |
// is equivalent to | |
function asyncLoop(generator) { | |
const gen = generator(); | |
generatorRunner(gen); | |
} | |
function isThenable(fn) { | |
return typeof fn.then === "function"; | |
} | |
function generatorRunner(generator) { | |
const firstStep = generator.next(); | |
const step = { | |
next: () => generator.next(), | |
current: firstStep, | |
}; | |
generatorLoop(step); | |
} | |
function generatorLoop(step) { | |
if (step.current.value === void 0) { | |
return; | |
} | |
if (isThenable(step.current.value)) { | |
step.current.value.then(() => { | |
const next = step.next(); | |
step.current = next; | |
generatorLoop(step); | |
}); | |
} else { | |
const next = step.next(); | |
step.current = next; | |
generatorLoop(step); | |
} | |
} | |
asyncLoop(function* () { | |
for (let i = 0; i < 5; i++) { | |
console.log(i); | |
yield delay(2000); | |
yield "test"; // not promise | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment