js中的Generators函数
2024-08-30 21:23:40
js中的Generators函数
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 }
捕获异常
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())
传递值给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现在才有用
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
遍历generator函数
function *test() {
yield 1;
yield 2;
yield 3;
} for(let item of test()) {
console.log(item);
} // 1 2 3
最新文章
- iOS开发之浅谈MVVM的架构设计与团队协作
- npm提速
- android Gui系统之SurfaceFlinger(3)---SurfaceFlinger
- delphi 数组类型与数组指针的巧妙利用
- 从零开始学JAVA(05)-连接数据库MSSQL(JDBC代码篇)
- java枚举enum
- 被sjy带刷题#1
- Query插件之ajaxFileUpload使用方法——input.change()事件的时候实现文件上传
- [NOIP模拟赛]约会date LCA(顺便填坑)
- Python实战之set学习笔记及简单练习
- .net 工程中引用出现感叹号
- 打包github上的项目,并在本地使用
- javascript最全最好的判断数组的方法
- 【adb】执行adb devices 设备offline
- sql查询语句时怎么把几个字段拼接成一个字段
- python之发送邮件~
- 如何将在线电子书保存为pdf格式
- MUI---IOS切换到后台继续播放音乐
- mysql日志配置
- 关于浏览器对静态HTML页面的缓存问题
热门文章
- OpenCV人脸检测并把图片写成avi视频
- hdu 5980 Find Small A(水,模拟)
- 一个html+js+ashx+easyui+ado.net权限管理系统
- 【lightoj-1026】Critical Links(桥)
- 设备上下文-CDC绘图细节
- Android使用Http协议访问网络——HttpConnection
- python3 csv数据读入/写出
- 《DSP using MATLAB》示例Example7.18
- django的manytomany总结
- 笔记:开源协议 Apache 2 和 GPL 兼容