|
| 1 | +/*** |
| 2 | +Bindings to async iterators, a way to do async iteration in JavaScript. |
| 3 | +
|
| 4 | +See [async iterator protocols](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols) on MDN.*/ |
| 5 | + |
| 6 | +/** |
| 7 | +The type representing an async iterator. |
| 8 | +*/ |
| 9 | +type t<'a> |
| 10 | + |
| 11 | +type value<'a> = { |
| 12 | + /** |
| 13 | + Whether there are more values to iterate on before the iterator is done. |
| 14 | + */ |
| 15 | + done: bool, |
| 16 | + /** |
| 17 | + The value of this iteration, if any. |
| 18 | + */ |
| 19 | + value: option<'a>, |
| 20 | +} |
| 21 | + |
| 22 | +/** |
| 23 | +`next(asyncIterator)` |
| 24 | +
|
| 25 | +Returns the next value of the iterator, if any. |
| 26 | +
|
| 27 | +See [async iterator protocols](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols) on MDN. |
| 28 | +
|
| 29 | +## Examples |
| 30 | +- A simple example, getting the next value: |
| 31 | +```rescript |
| 32 | +let {done, value} = await someAsyncIterator->AsyncIterator.next |
| 33 | +``` |
| 34 | +
|
| 35 | +- Complete example, including looping over all values: |
| 36 | +```rescript |
| 37 | +// Let's pretend we get an async iterator returning ints from somewhere. |
| 38 | +@val external asyncIterator: AsyncIterator.t<int> = "someAsyncIterator" |
| 39 | +
|
| 40 | +
|
| 41 | +let processMyAsyncIterator = async () => { |
| 42 | + // ReScript doesn't have `for ... of` loops, but it's easy to mimic using a while loop. |
| 43 | + let break = ref(false) |
| 44 | +
|
| 45 | + while !break.contents { |
| 46 | + // Await the next iterator value |
| 47 | + let {value, done} = await asyncIterator->AsyncIterator.next |
| 48 | +
|
| 49 | + // Exit the while loop if the iterator says it's done |
| 50 | + break := done |
| 51 | +
|
| 52 | + // This will log the (int) value of the current async iteration, if a value was returned. |
| 53 | + Console.log(value) |
| 54 | + } |
| 55 | +} |
| 56 | +``` |
| 57 | +*/ |
| 58 | +@send |
| 59 | +external next: t<'a> => promise<value<'a>> = "next" |
0 commit comments