Created
December 17, 2021 14:21
-
-
Save aminnairi/36b67fd46ecb4abae242f2b8ca879281 to your computer and use it in GitHub Desktop.
Asynchronous Recursive Generator
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
// Générateur asynchrone récursif | |
async function* webservice(entity, index = 1) { | |
const response = await fetch(`https://jsonplaceholder.typicode.com/${entity}/${index}`); | |
if (response.ok) { | |
yield response.json(); | |
// Yield Star (yield*) | |
// Permet de renvoyer la valeur résolue d'un générateur dans un générateur | |
// Équivalent d'applatir une imbrication de génerateur les uns dans les autres | |
yield* webservice(entity, index + 1); | |
} | |
} | |
async function main() { | |
for await (const user of webservice("users")) { | |
console.log(user.username); | |
} | |
} | |
main().catch(error => { | |
console.error(error.message); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment