Skip to content

Instantly share code, notes, and snippets.

@yairEO
Created March 19, 2022 14:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yairEO/9204a5f22d6a3c5abe58d4cff76ca4d7 to your computer and use it in GitHub Desktop.
Save yairEO/9204a5f22d6a3c5abe58d4cff76ca4d7 to your computer and use it in GitHub Desktop.
Async iterators
const delay = ms => new Promise(resolve => setTimeout(resolve, ms))
const inc = async i => (await delay(500), ++i)
const foo = async () => {
for(let i = 1; i <= 5; i = await inc(i))
console.log(i) // prints 1, 2, 3, 4, 5 with a delay
}
foo()
const delay = ms => new Promise(resolve => setTimeout(resolve, ms))
const dec = async i => (await delay(500), --i)
const foo = async () => {
let i = 5;
while(i = await dec(i))
console.log(i) // prints 4, 3, 2, 1 with a delay
}
foo()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment