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>
  • 相关阅读:
    重要常识
    ORACLE EBS中有些VIEW经常被OU屏蔽掉数据
    如何使用ftp从Metalink上下载补丁
    SO做了Booked之后,一直处理于“已延交”,发运事务处理的活动区变灰
    WIP模块常用表结构
    BOM查看多个物料下的子物料组件
    OE模块常用表结构
    如何诊断OM中的订单出现的问题
    INV模块常用表结构
    OM定义运费和特别费用类型
  • 原文地址:https://www.cnblogs.com/ashen1999/p/12559862.html
Copyright © 2011-2022 走看看