zoukankan      html  css  js  c++  java
  • generator,yield个人理解

    实验代码:

     1   function test1(arg){
     2         setTimeout(function(){
     3             // it.next(arg);
     4             console.log('先执行,并不触发');
     5         },200)
     6     }
     7     
     8     function test2(){
     9         setTimeout(function(){
    10             it.next('第一个')
    11         },0)
    12     }
    13   // 编写一个Generator;
    14     function *gen(){
    15         var a = yield test1('hhhhhhhh');
    16         console.log(a);
    17         var b = yield test2();
    18         console.log(b);
    19     }
    20 
    21     var it = gen();

    1.代码存在一个gen()函数, 第14行 存在两个yield 语句,(15,17)

    2. 执行gen()函数(21行),以为是Generator函数,所以函数体内语句不会执行,只是返回一个迭代器,

    3.在console 中执行 it.next(),

    gen函数会执行到第一个yield语句(15行),gen函数在此停止,并且触发test1函数,输出 "先执行,并不触发",

    4. 再执行 it.next(),gen()函数从刚才停止位置开始执行: 16~17行

    因为a无返回值,所以首先输出的是 undefined;

    执行到17行,gen()函数理应在此停止,因为触发的test2 函数体内触发了 it.next(‘第一个’),所以gen()函数返回值并且继续向下执行;

    it.next() 在test1,test2 函数中的作用是:返回值给当前yield,并且触发下一个 yield 执行

    取消test1中注释的 it.next(arg), 触发gen() 执行会一直执行到gen()函数结束

    问题点: 

    1.test1, test2 中的it.next()并不输出 {value: 'undefined', done: false},

    2. 在 test1 中可以获取下一个yield 中的 {value: 'undefined', done: false}

     3. it.next() 产生的 {value: 'undefined', done: false}, 其中的value 就是其触发的yield 后面跟得表达式产生的值;

  • 相关阅读:
    Diagnostic Viewer 显示空白
    ROS 的一些常用命令行功能
    ROS学习(更新中~)
    ubuntu坑(持续更新~)
    PHP延迟静态绑定:static关键字
    php实战正则表达式:验证手机号
    mysql 查询日志
    索引对更新语句速度影响很大
    给table设置滚动条
    PHP 对字符串进行十六进制替换 invalid character in attribute value
  • 原文地址:https://www.cnblogs.com/tatelZhang/p/7750020.html
Copyright © 2011-2022 走看看