异步迭代器Symbol.asyncIterator for await

274 阅读1分钟

记录获取全部数据,使用迭代器;

 **Symbol.asyncIterator** 符号指定了一个对象的默认异步迭代器。如果一个对象设置了这个属性,它就是异步可迭代对象,可用于[for await...of](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of)循环。

执行 Generator 函数会返回一个遍历器对象,也就是说,Generator 函数除了状态机,还是一个遍历器对象生成函数。返回的遍历器对象,可以依次遍历 Generator 函数内部的每一个状态。

for...of循环可以自动遍历 Generator 函数运行时生成的Iterator对象,且此时不再需要调用next方法。

除了for...of循环以外,扩展运算符(...)、解构赋值和Array.from方法内部调用的,都是遍历器接口。这意味着,它们都可以将 Generator 函数返回的 Iterator 对象,作为参数。

class GetList {    
index: number;    
storp: number;    
size: number;    
    constructor(index:number,size:number){        
        this.index = index;        
        this.size = size;       
        this.storp = Infinity;   
     }    
    async *[Symbol.asyncIterator](){        
        for(let i = 1;i< this.storp;i++){           
         this.index++           
         yield this.getTableList({pageIndex:this.index,pageSize:this.size,bm_Name:''})     
       }    
    }  
      private getTableList(params:object){   
          return   http.request({           
                     url:"/XXX/SearchFilesInfo",           
                     method:'GET',            
                     params:params      
          })   
 }
}

(async () => {  
 const getlist = new GetList(0,3)   
 for await (let i of getlist){
        //DataInfo每次返回长度
        //这里的i 相当于promise 使用async await 的值 gitList 本身返回一个Promise  
        //yield 返回的如果不是promise,会包装成promise;   
     if(i.ResData.DataInfo<3 || !i.ResData.DataInfo){         
           getlist.storp = 0       
     }else{            
        list.value =  list.value.concat(i.ResData.DataInfo)      
     }   
 }
})();