其他分享
首页 > 其他分享> > ES9(2018)——For await of

ES9(2018)——For await of

作者:互联网

ES9中异步操作集合是如何遍历的呢?

function Gen(time){
    return new Promise((resolve,reject)=>{
        setTimeout(function(){
            resolve(time);
        },time)
    })
}

function test(){
    let arr=[Gen(2000),Gen(100),Gen(3000)]
    for (let item of arr){
        console.log(Date.now(),item.then(console.log))
    }
}

test();
//1568603598236 Promise{<pending>}
//1568603598244 Promise{<pending>}
//1568603598245 Promise{<pending>}
//100
//2000
//3000

//for of解决不了异步操作集合的遍历问题

async function test(){
    let arr=[Gen(2000),Gen(100),Gen(3000)]
    for (let item of arr){
        console.log(Date.now(),await item.then(console.log))
    }
}

test();
//2000
//1568603598254 undefined
//100
//1568603598255 undefined
//3000
//1568603598256 undefined


//ES9
async function test(){
    let arr=[Gen(2000),Gen(100),Gen(3000)]
    for await (let item of arr){
        console.log(Date.now(),item)
    }
}

test();
//1568603598254 2000
//1568603598255 100
//1568603598256 3000


//for of 是用来遍历同步操作的,如果集合里有异步操作,是不能拿到正确结果的
//await for of 才是正儿八经的操作异步集合的

const obj={
    count:0,
    Gen(item){
        return new Promise((resolve,reject)=>{
            setTimeout(function(){
                resolve({done:false,value:time});
            },time)
        })
    },
    [Symbol.asyncIterator](){
        let self=this;
        return{
            next(){
                self.count++;
                if(self.count<4){
                    return self.Gen(Math.random()*1000)
                }else{
                    return Promise.resolve({
                        done:true,
                        value:''
                    })
                }
            }
        }
    }
}

async function test(){
    for await(let item of obj){
        console.log(Date.now(),item)
    }
}
test();
//1568603598254 392.3280054645453
//1568603598255 315.7491413397087
//1568603598256 436.94297753984836

 

标签:arr,await,ES9,item,let,2018,test,Gen,3000
来源: https://www.cnblogs.com/sunnywindycloudy/p/13054963.html