Skip to content

Instantly share code, notes, and snippets.

@aminnairi
Last active December 17, 2021 14:16
Show Gist options
  • Save aminnairi/4a962b26a0132ac5444e73dc95820279 to your computer and use it in GitHub Desktop.
Save aminnairi/4a962b26a0132ac5444e73dc95820279 to your computer and use it in GitHub Desktop.
Asynchronous Generator example using the JSONPlaceholder API
// 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