es2018 異步迭代器

參考文章:https://blog.csdn.net/songxiugongwang/article/details/83243311

異步迭代器結構如下圖:

const obj = {
    [Symbol.asyncIterator]: () => {
        const items = [`j`, `u`, `s`, `t`, `j`, `a`, `v`, `a`, `c`];
        return {
            next: () => {
                return new Promise((resolve, reject) => {
                    setTimeout(() => {
                        resolve({
                            done: items.length === 0,
                            value: items.shift()
                        })
                    }, 1000)
                })
            }
        }
    }
}

遍歷迭代器: 

async function process(array) {
    for await (let i of array) {
        console.log(i + 'abc') //i是返回的value值
    }
}

調用就是process(obj),陸續輸出各個字母

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章