异步迭代器从10.0.0版本开始出现在Node中,在本文中,我们将讨论异步迭代器的作用以及它们可以在哪里使用。什么是异步迭代器异步迭代器其实就是前面迭代器的异步版本。当我们不知道迭代的值和最终状态时,可以使用异步迭代器。两者的区别在于,我们得到的promise最终会被分解成一个普通的{value:any,done:boolean}对象,异步迭代器可以通过for-await-of循环进行处理。就像for-of循??环用于同步迭代器一样。constasyncIterable=[1,2,3];asyncIterable[Symbol.asyncIterator]=asyncfunction*(){for(leti=0;i{constreq=https.get(url,asyncfunction(res){if(res.statusCode>=400){returnreject(newError(`HTTPStatus:${res.statusCode}`));}try{letbody='';/*替换res.on来监听stream中的数据,可以使用for-await-of,将datachunk追加到responsebody的其余部分*/forawait(constchunkofres){body+=chunk;}//处理response没有的情况aresponsebodyif(!body)resolve({});//需要解析文本得到json因为是字符串constresult=JSON.parse(body);resolve(result);}catch(error){reject(error)}});awaitreq;req.end();});}该代码通过向CatAPI(https://thecatapi.com/)发出请求来获取一些猫的图片。还添加了7秒的延迟,以防止频繁访问catAPI,因为那是极不道德的。functionfetchCatPics({limit,page,done}){returnhomebrewFetch(`https://api.thecatapi.com/v1/images/search?limit=${limit}&page=${page}&order=DESC`).然后(body=>({value:body,done}));}functioncatPics({limit}){return{[Symbol.asyncIterator]:asyncfunction*(){letcurrentPage=0;//5页后停止while(currentPage<5){try{constcats=awaitfetchCatPics({currentPage,limit,done:false});console.log(`Fetched${limit}cats`);yieldcats;currentPage++;}catch(error){console.log('有一直是错误获取所有的猫!');console.log(error);}}}};}(asyncfunction(){try{forawait(letcatPicPageofcatPics({limit:10})){console.log(catPicPage);//每次请求之间等待7秒awaitnewPromise(resolve=>setTimeout(resolve,7000));}}catch(error){console.log(error);}})()这样我们会自动获取一个整体每7秒翻页一次猫图片。在页面之间导航的一种更常见的方法是实现next和previous方法并将它们公开为控件:functionactualCatPics({limit}){return{[Symbol.asyncIterator]:()=>{letpage=0;return{next:function(){page++;returnfetchCatPics({page,limit,done:false});},previous:function(){if(page>0){page--;returnfetchCatPics({page,limit,done:false});}returnfetchCatPics({page:0,limit,done:true});}}}};}try{constsomeCatPics=actualCatPics({limit:5});const{next,previous}=someCatPics[Symbol.asyncIterator]();next().then(console.log);next().then(console.log);previous().then(console.log);}catch(error){console.log(error);}作为您可以看到,当您想要获取数据页或在程序的UI上进行无限滚动等操作时,异步迭代器非常有用。这些功能在Chrome63+、Firefox57+、Safari11.1+中可用。