JaneChelle | Blog JaneChelle | Blog

执着于理想,纯粹于当下

目录
Generator函数
/      

Generator函数

一、说明

1.概念:

  1. ES6 提供的解决异步编程的方案之一
  2. Generator 函数是一个状态机,内部封装了不同状态的数据
  3. 用来生成遍历器对象
  4. 可暂停函数(惰性求值),yield 可暂停。next 方法可启动。每次返回的是 yield 后的表达式结果

2.特点:

function 与函数名之间有一个星号

内部用 yield 表达式来定义不同的状态

例如:

    function* generatorExample() {
        let result = yield 'hello';//状态值为hello
        yield 'generator';//状态值为generator
    }

generator 函数返回的是指针对象(接 11 章节里 iterator),而不会执行函数内部逻辑

调用 next 方法函数内部逻辑开始执行,遇到 yield 表达式停止,返回 value, yield 后的表达式结果/undefined, done

再次调用 next 方法会从上一次停止时的 yield 处开始, 直到最后

yield 语句返回结果通常为 undefined,当 调用 next 方法时, 传参内容 会作为启动时 yield 语句的返回值。

3.代码

牛刀小试

 function* generatorExample() {
        console.log('开始执行');
        let result = yield 'hello';//状态值为hello
        console.log('暂停后,再次执行');
        yield 'generator';//状态值为generator
        console.log('遍历完毕了。。。。');
        return '返回的结果'
    }
    let MG = generatorExample(); //返回的是指针对象
    console.log(MG); // 遍历器对象
    let result = MG.next(); //函数执行,遇到yield暂停
    console.log(result); //{value: "heLlo", done: false}
    result = MG.next(); //函数再次启动
    console. log(result); // {value: 'generator', done: false}
    result = MG.next();
    console. log(result); // {value: undefined, done: true} 表示函数内部状态已经遍历完毕

对象的 symbol.iterator 属性,指向遍历器对象

    let obj = {
        username: 'kobo',
        age: 18
    }
    obj[Symbol.iterator] = function* myTest() {
            yield 1;
            yield 2;
            yield 3;
    }
    for (let i of obj){
        console.log(i);
    }

4.案例

需求:

  1. 发送 AJAX 请求获取新闻内容。
  2. 新闻内容获取成功后再次发送请求,获取对应的新闻评论内容。
  3. 新闻内容获取失败则不需要再次发送请求。
function getNews(url) {
        $.get(url, function (data) {
            let commentsUrl = data.commentsUrl;
            let url = 'http://localhost:3000' + commentsUrl;
            sx.next(url);
        })
    }
    function* sendXml(){
        let url = yield  getNews('http://localhost:3000/news?id=3');
        yield getNews(url);
    }
    // 获取遍历器对象
    let sx = sendXml();
    sx.next();