23 # generator 的使用

简介: 23 # generator 的使用

1、类数组:长的像数组

const likeArray = {
    0: "a",
    1: "b",
    2: "c",
    3: "d",
    length: 4
};

可以 Array.from 将类数组转为数组

Array.from(likeArray) // [ 'a', 'b', 'c', 'd' ]

也可以使用拓展运算符:原理就是遍历这个对象 将结果放到数组中,这个数组必须有个遍历器。

[...likeArray]

likeArray 是类数组并且没有遍历器不能迭代遍历,执行会报错:object is not iterable

下面实现 likeArray 的迭代器(数组里面是有 Symbol.iterator 的)

我们给 likeArray 添加这个迭代器

likeArray[Symbol.iterator] = function () {
    // 返回一个遍历器对象,需要有一个 next 方法,不停的调用
    let i = 0;
    return {
        // 这里用箭头函数让里面的this指向 likeArray
        next: () => {
            return {
                value: this[i],
                // done 为 true 表示完成
                done: i++ === this.length
            };
        }
    };
};
console.log([...likeArray]);

2、使用 generator 改造 likeArray 的迭代器

* 表示该函数是 generator 函数,generator 生成器生成的叫遍历器(迭代器)

likeArray[Symbol.iterator] = function* () {
    let i = 0;
    while (i !== this.length) {
        // yield 表示产出,固定语法,配合着 * 来使用
        yield this[i++];
    }
};
console.log([...likeArray]);

3、generator 的使用

普通函数默认会从头到尾执行没有暂停的功能,generator 函数是 es6 提供的语法,如果碰到 yield 就会暂停执行(redux-saga、koa1 中有用到)

function* read() {
    yield 1;
    yield 2;
    yield 3;
}
let it = read(); // it 就是迭代器,迭代器上面有个 next 方法
console.log(it.next()); // { value: 1, done: false }
console.log(it.next()); // { value: 2, done: false }
console.log(it.next()); // { value: 3, done: false }
console.log(it.next()); // { value: undefined, done: true }
console.log(it.next()); // { value: undefined, done: true }

可以自己循环

let flag = false;
do {
    let { value, done } = it.next();
    flag = done;
    console.log("value--->", value);
} while (!flag);

4、yield 可以有返回值

function* read() {
    let a = yield 1;
    console.log("a---->", a);
    let b = yield 2;
    console.log("b---->", b);
    let c = yield 3;
    console.log("c---->", c);
    return c;
}
let it = read();
// next 是给上一次 yield 传参
it.next("k1"); // 第一次传参没有意义,上一次没有 yield
it.next("k2");
it.next("k3");
it.next("k4");

5、generator 的应用

比如:下面使用 generator 去读取两个文件的

const fs = require("fs").promises;
// 代码更像是同步的,但是执行还是异步的
function* read() {
    try {
        let name = yield fs.readFile("./file/name.txt", "utf-8");
        let age = yield fs.readFile("./file/age.txt", "utf-8");
        return { name, age };
    } catch (error) {
        console.log("error---->", error);
    }
}
let it = read();
let { value, done } = it.next();
value.then((data1) => {
    console.log("name---->", data1);
    let { value, done } = it.next(data1);
    value.then((data2) => {
        let { value, done } = it.next(data2);
        console.log("age---->", data2);
        console.log("return---->", value);
        // 还可以抛出异常
        // it.throw("泰裤辣");
    });
});

抛出异常:

目录
相关文章
|
Linux Windows
Nomachine 最简安装与使用指南
这是一篇2022年Nomachine软件的极简安装与使用指南,包括Windows和Linux系统下的安装步骤,以及如何在Windows系统上通过Nomachine远程控制Linux系统的方法。
Nomachine 最简安装与使用指南
|
机器学习/深度学习 编解码
Sora视频重建与创新路线问题之通过多尺度策略提升视频的生成质量该如何操作
Sora视频重建与创新路线问题之通过多尺度策略提升视频的生成质量该如何操作
365 5
|
自然语言处理
要求CHATGPT高质量回答的艺术:提示工程技术的完整指南—第 16 章:总结提示
要求CHATGPT高质量回答的艺术:提示工程技术的完整指南—第 16 章:总结提示
259 0
|
Shell Linux 开发工具
10.3.2 【Linux】历史命令:history
10.3.2 【Linux】历史命令:history
515 0
|
前端开发 Ruby Python
|
测试技术 Linux
Linux性能测试 top衍生命令 atop/htop/slaptop
1. Atop Atop 是一个类似 top 的工具,但比 top 更有料。通过 Atop,你能够监视 Linux 系统的性能状况,包括进程活动、CPU、内存、硬盘、网络等方面的使用情况等。   2. htop htop——一个可以让用户与之交互的进程查看器。
1776 0
|
9天前
|
域名解析 人工智能 Linux
|
19天前
|
Linux Go 开发工具
手机上跑 DeepSeek 智能体:开源安卓客户端 DSH Go 安装与使用指南
DSH Go 是一款开源安卓客户端,将 DeepSeek Harness 智能体引擎装进手机:免 Root、免 Termux,一键安装即用;支持本机运行(内置 Ubuntu+Node.js)或远程接管电脑会话;具备插话打断、过程折叠、屏幕操控、端到端加密分享等特色功能,真正实现智能体“口袋化”。
17555 63
|
17天前
|
人工智能
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置
进不去 Antigravity 或 Gemini,提示所在地区不可用?三步查清 Google 账号关联地区、官方更正表单理由选法与改区注意事项。
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置

热门文章

最新文章