Sync iterables and [[asyncIterator]]

Herbert Vojčík herby at mailbox.sk
Sun Aug 19 21:34:27 UTC 2018


Hello!


Lately, I created this in one project:

export async function* zip (...iterables) {
     for (const iterators = iterables.map(each => (each[Symbol.iterator] 
|| each[Symbol.asyncIterator]).apply(each)); ;) {
         const all = await Promise.all(iterators.map(async each => await 
each.next()));
         if (all.some(each => each.done)) break;
         yield all.map(each => each.value);
     }
}

It was sync generator before, but once one of the entries became async 
generator, I changed the zip itself to be async.

My question is to the pretty ugly

   const iterators = iterables.map(each => (each[Symbol.iterator] || 
each[Symbol.asyncIterator]).apply(each))

Is there some more idiomatic way to find "any iterator; sync or async" / 
alternatively, could sync iterator return respective [[asyncIterator]] 
as well, just promisifying the result (as a sort of proto-proposal of sort)?

Or is there some easy way to change sync iterable to async iterable, so 
I could change the other ones at call site?


Thanks, Herby


More information about the es-discuss mailing list