Generator函数通过function*定义,调用后返回迭代器,使用next()方法可逐段执行,每次遇到yield暂停并返回值,再次调用继续执行,支持传参、提前结束和错误注入,适用于惰性求值与异步控制。

JavaScript 中的 Generator 函数是一种特殊函数,可以暂停和恢复执行。调用 Generator 函数会返回一个迭代器对象,通过该对象提供的方法来控制函数的执行。
调用 Generator 函数的基本方式
定义一个 Generator 函数使用 function* 语法:
function* myGenerator() {
yield 1;
yield 2;
return 3;
}
调用它会返回一个迭代器:
const gen = myGenerator();
使用 next() 方法逐步执行
Generator 最主要的方法是 next(),用于启动或恢复执行:
第一次调用 gen.next():执行到第一个 yield,返回 { value: 1, done: false }第二次调用:执行到第二个 yield,返回 { value: 2, done: false }第三次调用:执行完函数体,返回 { value: 3, done: true }
示例:
console.log(gen.next()); // { value: 1, done: false }
console.log(gen.next()); // { value: 2, done: false }
console.log(gen.next()); // { value: 3, done: true }
向 next() 传参
可以通过 next(value) 向 Generator 内部传递数据,这个值会成为上一个 yield 表达式的返回值:
function* genWithInput() {
const a = yield ‘input?’;
console.log(a); // 接收 next 传入的值
}const g = genWithInput();
g.next(); // 启动,停在 yield ‘input?’
g.next(‘hello’); // 将 ‘hello’ 赋给变量 a
提前结束:return() 和 throw()
gen.return(value):立即结束 Generator,返回 { value: value, done: true }gen.throw(error):在暂停处抛出异常,可被内部 try/catch 捕获
示例:
gen.return(99); // { value: 99, done: true },后续 next 不再执行
基本上就这些。Generator 的核心就是通过 next() 驱动执行,配合 yield 实现惰性求值、异步流程控制等高级用法。
以上就是js调用generator的方法的详细内容,更多请关注php中文网其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1535763.html
微信扫一扫
支付宝扫一扫