Promise<Iterator<Item>> or Iterator<Promise<Item>> ?
None. It is still not approved, but current implementations return something else. Chris Koval wrote about asynchronous generators and links Jafar Husain AsyncGenerator Offer for ES7 . EDIT . We have tc39 offer and babel support !
Let define some types (simplified):
interface Iterator<T> { Iteration<T> next(); } type Iteration<T> = { done: boolean, value: T }
We are looking for something that can be used as follows:
for (;;) { var iteration = await async_iterator.next(); if (iteration.done) { return iteration.value; } else { console.log(iteration.value); } }
An Iterator<Promise<T>> creates synchronous iterations whose values ββare Promises. It can be used as follows:
for (;;) { var iteration = iterator_promise.next(); if (iteration.done) { return await iteration.value; } else { console.log(await iteration.value); } }
A Promise<Iterator<T>> is just a regular synchronous iterator, starting from the future:
var iterator = await promise_iterator; for (;;) { var iteration = iterator.next(); if (iteration.done) { return iteration.value; } else { console.log(iteration.value); } }
So Iterator<Promise<T>> and Promise<Iterator<T>> not suitable. Asynchronous generators currently return AsyncIterator instead:
interface AsyncIterator<T> { Promise<Iteration<T>> next(); }
Which makes perfect sense. Going to the next element of the iterator is an asynchronous operation, and it can be used exactly as we wanted.
How to use Async generators?
Babeljs.io is already compiling async generators. Babeljs.io/repl example
EDIT : no preset on babeljs.io compiles async generators, since babel 6, babel-plugin-transform-regenerator supports it with the {asyncGenerators:true} option.
EDIT : see transform-async-generator-functions babel 6 plugin.
function delay(timeout, val) { return new Promise(resolve => setTimeout(resolve, timeout, val)); } async function* asyncGenerator() { for (var i = 0; i < 5; i++) { await delay(500); yield i; } } async function forAwait(iter, fn) { for (;;) { let iteration = await iter.next(); if (iteration.done) return iteration.value; await fn(iteration.value); } } async function main() { console.log('Started'); await forAwait(asyncGenerator(), async item => { await delay(100); console.log(item); }); console.log('End'); } main();
There is a suggestion for a convenient for await loop for await asynchronous iterators (described in Asynchronous iteration ):
for await (let line of readLines(filePath)) { print(line); }
Update:
Unfortunately, async-await did not become part of ECMAScript 2016 . At least await mentions a reserved word for future use.
Update:
Similar offers: