js中的Generators函数

  1. generator一般操作

    generator函数的作用就是函数体分段执行,yield表示分隔点
    function *test() {
    console.log(1);
    yield 1;
    console.log(2);
    yield 2;
    console.log(3);
    yield 3;
    } var g = test(); console.log(g.next()) // { value: 1, done: false }
    console.log(g.return(2)) // { value: 2, done: true },return不执行任何函数体,直接结束函数执行
    console.log(g.next()) // { value: undefined, done: true }
  2. 捕获异常

    function *test() {
    try {
    yield 1;
    yield 2;
    } catch (error) {
    console.log(error.message);
    }
    } var g = test(); console.log(g.next())
    console.log(g.throw(new Error("Error"))) // { value: undefined, done: true } 捕获异常,同时结束函数执行
    console.log(g.next())
  3. 传递值给generator函数

    function *test() {
    var s;
    s = yield;
    console.log(s);
    s = yield;
    console.log(s);
    } var g = test(); g.next(); // 第一次调用next会无视传递的value
    g.next(1); // 第二次传递value现在才有用
  4. yield代理到其他的generator函数

    function *test() {
    yield 1;
    yield *other();
    } function *other() {
    yield 2;
    yield 3;
    }
    var g = test(); console.log(g.next()) // 1
    console.log(g.next()) // 2
    console.log(g.next()) // 3
  5. 遍历generator函数

    function *test() {
    yield 1;
    yield 2;
    yield 3;
    } for(let item of test()) {
    console.log(item);
    } // 1 2 3

最新文章

  1. iOS开发之浅谈MVVM的架构设计与团队协作
  2. npm提速
  3. android Gui系统之SurfaceFlinger(3)---SurfaceFlinger
  4. delphi 数组类型与数组指针的巧妙利用
  5. 从零开始学JAVA(05)-连接数据库MSSQL(JDBC代码篇)
  6. java枚举enum
  7. 被sjy带刷题#1
  8. Query插件之ajaxFileUpload使用方法——input.change()事件的时候实现文件上传
  9. [NOIP模拟赛]约会date LCA(顺便填坑)
  10. Python实战之set学习笔记及简单练习
  11. .net 工程中引用出现感叹号
  12. 打包github上的项目,并在本地使用
  13. javascript最全最好的判断数组的方法
  14. 【adb】执行adb devices 设备offline
  15. sql查询语句时怎么把几个字段拼接成一个字段
  16. python之发送邮件~
  17. 如何将在线电子书保存为pdf格式
  18. MUI---IOS切换到后台继续播放音乐
  19. mysql日志配置
  20. 关于浏览器对静态HTML页面的缓存问题

热门文章

  1. OpenCV人脸检测并把图片写成avi视频
  2. hdu 5980 Find Small A(水,模拟)
  3. 一个html+js+ashx+easyui+ado.net权限管理系统
  4. 【lightoj-1026】Critical Links(桥)
  5. 设备上下文-CDC绘图细节
  6. Android使用Http协议访问网络——HttpConnection
  7. python3 csv数据读入/写出
  8. 《DSP using MATLAB》示例Example7.18
  9. django的manytomany总结
  10. 笔记:开源协议 Apache 2 和 GPL 兼容