box / box/box-node-sdk

Make PagingIterator support iterable protocol as well

Open
#528 2 comments 0 reactions 0 assignees View on GitHub
enhancement
Dominant language
TypeScript
Stars
199
Forks
123
Avg merge
1d 1h
Merged PRs (30d)
20

Description

### Is your feature request related to a problem? Please describe.

ES2018 supports for-await-of statements, which conveniently iterates over an async _iterable_ object.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of

`PagingIterator`s returned by enumerating methods of the SDK when `config.iterators` set to `true`, however, cannot be directly used in such statements since `PagingIterator` is just an async iterator, not an async iterable.
```javascript
const pageit = await client.folders.getItems(folder_id);
for await (const item of pageit) { // won't work
}
```

### Describe the solution you'd like

Among several approaches that we may come up with, the simplest one shall be making `PagingIterator` support the async iterable protocol as well.
It is as simple as adding the following method to `PagingIterator` class.
```javascript
[Symbol.asyncIterator]() { return this; }
```
Note: I am not sure this code is compatible with pre-ES2018 runtime which lacks definition for `Symbol.asyncIterator`.

I am following an idea described in the note in the corresponding MDN article.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols

### Describe alternatives you've considered

The suggested solution above has a flaw as the users of an iterable object might expect getting a fresh iterator every time one calls `@@asyncIterator` method, although it is not mandated by the specification.

It might be more pedantically correct if we had a separate iterable object and making all enumerating SDK methods return it instead of directly returning an iterator, but it is a breaking change.

### Additional context

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.