2

So I get Promise<AsyncIterableIterator<T>> and I need plain AsyncIterableIterator<T> how can I unwrap the AsyncIterableIterator<T> from under the promise?

Trident D'Gao
  • 18,973
  • 19
  • 95
  • 159

1 Answers1

1

Yes, it's actually quite simple. We want to implement the AsyncIterableIterator interface ourselves, and for every call to next we first unwrap the Promise.

function unwrapAsyncIterableIteratorPromise (input) {
  return {
    next (value) {
      return input.then((iterator) => iterator.next(value))
    },
    [Symbol.asyncIterator] () {
      return this
    }
  }
}

It's also on npm together with TypeScript typings:

https://www.npmjs.com/package/unwrap-async-iterable-iterator-promise

Linus Unnebäck
  • 23,234
  • 15
  • 74
  • 89