Skip to content

Instantly share code, notes, and snippets.

@sergiodxa
Last active August 29, 2015 14:21
Show Gist options
  • Save sergiodxa/1c495ab0d9a8210e8079 to your computer and use it in GitHub Desktop.
Save sergiodxa/1c495ab0d9a8210e8079 to your computer and use it in GitHub Desktop.
Generadores asíncronos
import xhr from 'promised-xhr';
async function* obtenerDatos () {
try {
let finised = false;
let page = 0;
while(!finished) {
page++;
const { body: data } = await xhr.get(`/api/resource?page=${page}`);
if (data.length < 10) finished = true;
yield data;
}
return false;
} catch (err) {
throw err;
}
}
let aIterator = obtenerDatos();
window.addEventListener('load', async function () {
const data = await aIterator.next().value;
// mostramos data en el DOM
});
$button.addEventListener('click', async function () {
const data = await aIterator.next().value;
if (data) {
// mostramos data en el DOM
} else {
// mostramos un mensaje de que no hay más datos
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment