How to iterate over the results of a generator function

前端 未结 2 364
一向
一向 2021-01-12 23:40

Is there a better way to iterate over the results of a generator, my for loop is ugly:

for(let job = readyJob.next(); !job.done; job = readyJob.next()){ } 
<         


        
相关标签:
2条回答
  • 2021-01-13 00:05

    for ... of is the elegant solution but not overall supported, however while (!(next = cursor.next()).done) { is a very cryptic, and one might ask himself, how come (var x = someFunctionCall()) is evaluated to true and another would answer welcome to javascript.

    For that reason and to and give the answer another shape, it can also be done using a recursive function.

    function loopThose(items) {
        const item = items.next();
    
        // doStuff(item);
    
        if (!item.done) {
            loopThose(items);
        }
    }
    

    A true benefit is when async, try catch and custom continue condition come into play:

    async function printKeys(items) {
        try {
           const item = await items.next();
           // doStuff(item);
           if (isConditionFulfil(item)) {
              await this.printKeys(items);
           }
        } catch (e){
    
        }
    }
    

    Where a generator function yields promises that might fail:

    function * list(){
      for (var i = 0; i<10; i++){
         yield fetch(buildResourceUrl(i)).then(res => res.json())
      }
    }
    
    0 讨论(0)
  • 2021-01-13 00:25

    Yes, if your environment already supports for...of:

    for (var job of readyJob) {
      // ...
    }
    

    If not, have seen this a couple of times:

    var next;
    while (!(next = readyJob.next()).done) {
       var job = next.value;
       // ...
    }
    
    0 讨论(0)
提交回复
热议问题