Last active
December 17, 2021 14:16
-
-
Save aminnairi/4a962b26a0132ac5444e73dc95820279 to your computer and use it in GitHub Desktop.
Asynchronous Generator example using the JSONPlaceholder API
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
// Générateur asynchrone | |
async function* webservice(entity) { | |
let index = 1; | |
while (true) { | |
try { | |
const response = await fetch(`https://jsonplaceholder.typicode.com/${entity}/${index}`); | |
if (!response.ok) { | |
throw new Error("Not found"); | |
} | |
yield response.json(); | |
index = index + 1; | |
} catch (error) { | |
break; | |
} | |
} | |
} | |
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