当前位置: 首页 > Web前端 > HTML

ES9(一)——对于

时间:2023-04-02 11:47:54 HTML

类的awaitQes9中异步操作的集合是如何遍历的?如何解决这个问题?最终解决方案——for-await-offor-of和for-await-of的区别如何实现自定义数据结构的异步遍历?ES6-ES10学习图Q:ES9中异步操作的集合是如何遍历的?数组中的元素都是promise对象,没办法遍历。functionGen(time){returnnewPromise((resolve,reject)=>{setTimeout(function(){resolve(time)},time)})}functiontest(){letarr=[Gen(2000),Gen(1000),Gen(3000)]for(letitemofarr){console.log(Date.now(),item.then(console.log))}}test()//1597047404040Promise{}//1597047404040Promise{}//1597047404040Promise{}//1000//2000//3000这种遍历是先遍历出来,再执行pendingpromise。如何解决这个问题?在测试函数前加async,for-of遍历时在每个元素前加await,每个对象等待后执行下一个。functionGen(time){returnnewPromise((resolve,reject)=>{setTimeout(function(){resolve(time)},time)})}asyncfunctiontest(){letarr=[Gen(2000),Gen(1000),Gen(3000)]for(letitemofarr){console.log(Date.now(),awaititem.then(console.log))}}test()//2000//1597047766221未定义//1000//1597047768223undefined//3000//1597047768224undefined分析输出结果:先执行thenafterawait,返回2000后执行console.log返回时间戳,然后await的返回值为空,所以返回undefined虽然await让for-of暂停了,但是执行的顺序还是和我们想要的不一样。最终的解决方案——在Forawaitoftest函数前加上async关键字来完善for-offunctionGen(time){returnnewPromise((resolve,reject)=>{setTimeout(function(){resolve(time)},time)})}asyncfunctiontest(){letarr=[Gen(2000),Gen(100),Gen(3000)]forawait(letitemofarr){console.log(Date.now(),item)}}test()//15970486774292000//1597048677429100//15970486784293000for-of和for-await的区别-of用来遍历for-of和await的同步操作,如果有其他操作,会有一个输出序列错误forawaitof能够对异步集合进行操作。如何实现自定义数据结构的异步遍历?定义具有基本数据类型和承诺类型的对象。自定义一个[Symbol.asyncIterator]方法,使其成为可遍历的对象。使用forawaitof方法遍历constobj={count:0,Gen(time){returnnewPromise((resolve,reject)=>{setTimeout(function(){resolve({done:false,value:time})},time)})},[Symbol.asyncIterator](){letself=thisreturn{next(){self.count++if(self.count<4){returnself.Gen(Math.random()*1000)//retuen的返回值是gen函数resolve返回的对象}else{returnPromise.resolve({done:true,value:''})}}}}}asyncfunctiontest(){forawait(letitemofobj){console.log(Date.now(),item)}}test()//1597049702437292.73328473812523//1597049702574136.72074104961163//1597049703250675.51817ES69ES144布局学习