Last active
November 24, 2019 19:03
-
-
Save bisubus/3439c19279a74319a767d4168e42be83 to your computer and use it in GitHub Desktop.
Desugared generator & async generator functions (for..of & for await..of)
This file contains hidden or 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
|
This file contains hidden or 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
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(); | |
} | |
})(); |
This file contains hidden or 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
async function* asyncGenFn() { | |
let num = 1; | |
while (num <= 3) { | |
yield num++; | |
} | |
} | |
(async () => { | |
const asyncGen = asyncGenFn(); | |
for await (const num of asyncGen) { | |
console.log(num); | |
} | |
})(); |
This file contains hidden or 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
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(); | |
} | |
} |
This file contains hidden or 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
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