Symbol.iterator与Symbol.asyncIterator并用Example

2019-11-12 张宇童 学习日志

let obj = {
    count: 0,
    items: {
        names: ['小明', '笑话', '小草'],
        age: [19,20,30],
        haha: ['小小', '大大'],
    },
    Gen(time) {
        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: ''})
                }
            }
        }
    },
    [Symbol.iterator] () {
        let arr = this.items;
        let keys = Reflect.ownKeys(arr)
        let values = [];
        return {
            next() {
                if (!values.length) {
                    if (keys.length) {
                        values = arr[keys[0]]
                        keys.shift()
                    } else {
                        return { done: true, value: '' }
                    }
                }
                return {
                    value: values.shift(),
                    done: false
                }
            }
        }
    }
}

for (let i of obj) {
    console.log(i)
}

async function test() {
    for await (let i of obj) {
        console.log(i)
    }
}

test()

标签: javascript ES6

发表评论:

Powered by emlog