Skip to content

Instantly share code, notes, and snippets.

@gskachkov
Last active July 20, 2017 19:14
Show Gist options
  • Save gskachkov/b1be2d4335b602c05a7532d2f3859289 to your computer and use it in GitHub Desktop.
Save gskachkov/b1be2d4335b602c05a7532d2f3859289 to your computer and use it in GitHub Desktop.
async function* asyncRandomNumbers() {
// This is a web service that returns a random number
const url = 'https://www.random.org/decimal-fractions/?num=1&dec=10&col=1&format=plain&rnd=new';
while (true) {
const response = await fetch(url);
const text = await response.text();
yield Number(text);
}
}
var iter = asyncRandomNumbers();
iter.next()
.then(result => console.log('success:', result.value, result.done),
reason => console.log('error:', reason));
// success: 0.6191637358 false
iter.return('result-value')
.then(result => console.log('success:', result.value, result.done),
reason => console.log('error:', reason));
// success: result-value true
iter.throw('exception')
.then(result => console.log('success:', result.value, result.done),
reason => console.log('error:', reason));
// error: exception
async function example() {
for await (const number of asyncRandomNumbers()) {
console.log(number);
if (number > 0.95) break;
}
}
async generator* asyncRandomNumbersWrapper() {
yield* asyncRandomNumbers();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment