Proper use with ES6 generators and pagination

I thought about this a bit, and I cannot find a reasonable solution on how to do this. The problem statement is simple - write a generator that will lazily split the remote dataset. To simplify the situation, it is ideal that I would like a user of my library to see:

for (var user of users()) { console.log(user); } 

I can't seem to get the generator to work. I thought logic would work that way, but I can't figure out how to implement it.

 function* users() { while (canPaginate) { yield* getNextPageOfUsers() // This will need to return an array of users from an http request } } 

I am sure that I am thinking about something wrong here, but I can’t find examples of who uses such a generator (mostly people use it with static data or people who do something like async(function*(){...}) which is not quite what I am looking for). The important part here is that I want the end user to be able to use the data as described above.

-Vince

+6
source share
1 answer

Generators are functions that, in essence, are paused and returned to their callers. But when called, they must synchronously return a value or complete. Therefore, they cannot return the result of an asynchronous operation for the same reason that ordinary functions cannot return the result of an asynchronous operation.

As Benjamin noted, there is an ES7 proposal for asynchronous generators that would allow them to do this, but this is ES7 and is already noticeable in the future at this stage. The syntax of consumption is also affected (it is clear, it is important that people writing a call know that something is happening in async, we can’t have ordinary functions look synchronous when they are not).

According to the current sentence, your code using asynchronous function generators will look something like this:

 for (var user on users()) { console.log(user); } 

(Note on on instead of in or of .) But that can change.

+5
source

Source: https://habr.com/ru/post/980779/


All Articles