Created
March 5, 2019 05:06
-
-
Save alejandrolechuga/5d5dd6b189e3ebb9185be40bf1031fa5 to your computer and use it in GitHub Desktop.
Generador Infinito Asincrono
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<meta name="viewport" content="width=device-width"> | |
<title>JS Bin</title> | |
</head> | |
<body> | |
<div id="container"></div> | |
</body> | |
</html> |
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
// GENERADOR INFINITO ASINCRONO | |
// Asynchronous Infinite Generator | |
/* jshint esnext: true */ | |
// noprotect | |
// https://picsum.photos/200/300 | |
// stream | |
const container = document.getElementById('container'); | |
function delay(n) { | |
return new Promise((resolve) => { | |
setTimeout(resolve, n); | |
}); | |
} | |
function randomImage() { | |
return new Promise((resolve, reject) => { | |
const url = `https://picsum.photos/200/300?random=${Math.random()}`; | |
const img = document.createElement('img'); | |
img.onload = () => resolve(img); | |
img.onerror = reject; | |
img.src = url; | |
}) | |
} | |
function* infiniteGenerator() { | |
while(true) yield delay(100) | |
.then(() => { | |
return randomImage(); | |
}); | |
} | |
async function consumidor() { | |
for await (let img of infiniteGenerator()) { | |
container.appendChild(img); | |
} | |
} | |
consumidor(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment