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

 

上一篇:CORS跨域操作cookie


下一篇:166万人被骗3000万元!最近全网刷屏的网红游戏翻车了?