js 异步遍历器

92 阅读1分钟

js 异步遍历器

同步遍历器问题

function* fn(){
    yield 'AAA'
    yield 'BBB'
}
const sync = fn()
console.log(sync.next()) //{value:'AAA',done:false}
console.log(sync.next()) //{value:'BBB',done:false}
console.log(sync.next()) //{value:'undefined',done:false}

value 属性的返回值是一个 Promise 对象来放置异步操作,但是这也写很麻烦,语意比较绕

异步遍历器生成函数 Generator 函数返回一个同步遍历器,异步 Generator 函数的作用,是返回一个遍历器对象,在语法上,异步 Generator 函数就是 async 函数与 Generator 函数的结合

async function *fn(){
    yield new Promise(resolve=>resolve('AAA'));
    yield new Promise(resolve=>resolve('BBB'))
}
const asyncR = fn();
asyncR.next().then(res=>{
    console.log('res',res)
    return asyncR.next();
}).then(res=>{
    console.log('res',res)
    return asyncR.next();
}).then(res=>{
    console.log(res)
})
//执行结果
{value:"AAA",done:false}
{value:"BBB",done:false}
{value:undefined,done:true}

for await of

for...of 循环用于遍历同步的 Interactor 接口,新引入的 for await...of 循环,则是用于遍历异步的 Interactor 接口

    async function test(){
        for await (let item of asyncR){
            console.log(item)
        }
    }

案例

    //异步代码
    function Tiemr(t){  
        return new Promise(resolve=>{
            setTimeout(()=>{
                resolve(t)
            },t)
        })
    }
    //异步生成器
    async function *gen(){
        yield Tiemr(1000);
        yield Tiemr(2000);
        yield Tiemr(3000);
    }
    
    async function test(){
        let g = gen();
        let genArr = [g.next(2000),g.next(3000),g.next(4000)];
        //循环变量
        for await (let item of genArr){
            console.time('start')
            console.log('item',item)
            console.timeEnd('end')
        }
    }
    test()