3. generator&co

109 阅读1分钟

generator

console.log(Array.from({0:1,1:2,2:3, length:3}));
// 迭代器就表示他有一个next方法,能return一个包含value和done的对象
console.log([...{0:1,1:2,2:3, length:3, [Symbol.iterator]: function* () {
    yield 1;
    yield 2;
    yield 3;
}}])
console.log([...{0:1,1:2,2:3, length:3, [Symbol.iterator]: function() {
    let arr = this;
            let index = 0;
    return {
            next() { // 迭代时会调用next方法,必须要返回两个属性 {value, done}
                return { value: arr[index], done: index++ == arr.length }
            }
    }
}}])
console.log([...{0:1,1:2,2:3, length:3, [Symbol.iterator]: function* () {
    let index = 0;
    while(index !== this.length) {
        yield this[index];
    }
}}])

co的实现

function* read() {
    const a = yield fs.readFile("a.txt", "utf8");
    const b = yield fs.readFile(a, "utf8");
    return b;
}

// 同步迭代用for
// 异步迭代用递归
function co(it) {
    return new Promise((resolve, reject) => {
        function next(data) {
            let { value, done } = it.next(data);
            if(done) {
                return resolve(value);
            }
            Promise.resolve(value).then(data => {
                next(data);
            }, reject)
        }
        next();
    })
}


co(read()).then(data => {
    console.log(data);
})

  • async + await => co + generator 语法糖