Skip to content

Instantly share code, notes, and snippets.

@bisubus
Last active November 24, 2019 19:03
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 bisubus/3439c19279a74319a767d4168e42be83 to your computer and use it in GitHub Desktop.
Save bisubus/3439c19279a74319a767d4168e42be83 to your computer and use it in GitHub Desktop.
Desugared generator & async generator functions (for..of & for await..of)
function asyncGenFn() {
let num = 1;
return {
[Symbol.asyncIterator]() {
return this;
},
async next() {
return (num <= 3) ?
{ value: num++, done: false } :
{ value: undefined, done: true };
}
};
}
(async () => {
const asyncGen = asyncGenFn();
let result = await asyncGen.next();
while (!result.done) {
const num = result.value;
console.log(num);
result = await asyncGen.next();
}
})();
async function* asyncGenFn() {
let num = 1;
while (num <= 3) {
yield num++;
}
}
(async () => {
const asyncGen = asyncGenFn();
for await (const num of asyncGen) {
console.log(num);
}
})();
function genFn() {
let num = 1;
return {
[Symbol.iterator]() {
return this;
},
next() {
return (num <= 3) ?
{ value: num++, done: false } :
{ value: undefined, done: true };
}
};
}
{
const gen = genFn();
let result = gen.next();
while (!result.done) {
const num = result.value;
console.log(num);
result = gen.next();
}
}
function* genFn() {
let num = 1;
while (num <= 3) {
yield num++;
}
}
{
const gen = genFn();
for (const num of gen) {
console.log(num);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment