Genarator生成器

Generator

  • Generator生成器,是es6新增语法

  • 书写方式如下

    • function后加上*

    • yield 相当于return

    function* fruitslist() {
       yield 'grape';
       yield 'watermelon';
       yield 'mango'
    }
  • 将其返回值赋值给一个变量,得到一个Generator类型的数据,可遍历

  • 其中返回了next()方法

  • 在没有调用next()之前,生成器处于suspended状态

  • 调用next(),返回一个对象

    • 对象中第一个值为按顺序遍历到的返回值

    • 第二个值为判断是否遍历结束的布尔值

      fruits.next()
      {value: "grape", done: false}
      fruits.next()
      {value: "watermelon", done: false}
      fruits.next()
      {value: "mango", done: false}
      fruits.next()
      {value: undefined, done: true}
  • 当遍历结束后,生成器处于closed状态

  • 每当执行完一条yield语句就会停止执行

Generator遍历数组

  • 通过for..of..循环遍历

    const personlist = [
          {name: 'kris Wu', job: 'singer', age: 30},
          {name: 'ashen', job: 'student', age: 20},
          {name: 'tanX', job: 'programmer', age: 23}
      ];
    function* loop(arr) {
       for (let item of arr) {
           yield item
      }
    }

Generator发送ajax请求

  • 每一次yield都是在发送ajax请求

  • 一次yield执行结束便会暂停,等待下一次调用next()时再开始

  • 定义ajax函数,将url传入,请求成功后执行生成器返回的接口对象的next()方法

    <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.16.2/axios.min.js"></script>
    <script>
       function ajax(url) {
      //每次执行next()方法,都会首先将响应结果返回
           axios.get(url).then(res => getinfo.next(res.data))
      }

       function* getInfo() {
           console.log('fetching users');
           const users = yield ajax('http://api.github.com/users');
           console.log(users);
           console.log('fetching first user');
           const firstUser = yield ajax(`http://api.github.com/users${users[0].login}`);
           console.log(firstUser);
           console.log('fetching followers');
           const followers = yield ajax(firstUser.followers_url);
           console.log(followers);
      }

       const getinfo = getInfo();
       getinfo.next();
    </script>

猜你喜欢

转载自www.cnblogs.com/ashen1999/p/12559862.html
今日推荐