zoukankan      html  css  js  c++  java
  • 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>
  • 相关阅读:
    JProfiler_SN_8_x key
    java格式化百分比
    获取每月第一天最后一天 java
    java 获取昨天日期
    eclipse git提交代码
    SIT与UAT的分别
    Spring <context:annotation-config/> 说明
    Hibernate日期映射类型
    Oracle查询备注信息
    Log4J入门
  • 原文地址:https://www.cnblogs.com/ashen1999/p/12559862.html
Copyright © 2011-2022 走看看