Generator函数
概念
yield
运行逻辑
yield只能用在Generator函数里面
(function (){
yield 1;
})()
// SyntaxError: Unexpected numberyield在另外的表达式中,必须放在圆括号中
暂缓执行
next()
最后更新于
(function (){
yield 1;
})()
// SyntaxError: Unexpected number最后更新于
function* demo() {
console.log('Hello' + yield) // SyntaxError
console.log('Hello' + yield 123) // SyntaxError
console.log('Hello' + (yield)) // OK
console.log('Hello' + (yield 123)) // OK
}function* f() {
console.log('执行了!')
}
var generator = f();
setTimeout(function () {
generator.next()
}, 2000);function* foo(x) {
var y = 2 * (yield (x + 1));
var z = yield (y / 3);
return (x + y + z);
}
var a = foo(5);
a.next() // Object{value:6, done:false}
a.next() // Object{value:NaN, done:false}
a.next() // Object{value:NaN, done:true}
var b = foo(5);
b.next() // { value:6, done:false }
b.next(12) // { value:8, done:false }
b.next(13) // { value:42, done:true }