function 与函数名之间有一个星号
内部用 yield 表达式来定义不同的状态
例如:
function* generatorExample() {
let result = yield 'hello';//状态值为hello
yield 'generator';//状态值为generator
}
generator 函数返回的是指针对象(接 11 章节里 iterator),而不会执行函数内部逻辑
调用 next 方法函数内部逻辑开始执行,遇到 yield 表达式停止,返回 value, yield 后的表达式结果/undefined, done
再次调用 next 方法会从上一次停止时的 yield 处开始, 直到最后
yield 语句返回结果通常为 undefined,当 调用 next 方法时, 传参内容 会作为启动时 yield 语句的返回值。
牛刀小试
function* generatorExample() {
console.log('开始执行');
let result = yield 'hello';//状态值为hello
console.log('暂停后,再次执行');
yield 'generator';//状态值为generator
console.log('遍历完毕了。。。。');
return '返回的结果'
}
let MG = generatorExample(); //返回的是指针对象
console.log(MG); // 遍历器对象
let result = MG.next(); //函数执行,遇到yield暂停
console.log(result); //{value: "heLlo", done: false}
result = MG.next(); //函数再次启动
console. log(result); // {value: 'generator', done: false}
result = MG.next();
console. log(result); // {value: undefined, done: true} 表示函数内部状态已经遍历完毕
对象的 symbol.iterator 属性,指向遍历器对象
let obj = {
username: 'kobo',
age: 18
}
obj[Symbol.iterator] = function* myTest() {
yield 1;
yield 2;
yield 3;
}
for (let i of obj){
console.log(i);
}
需求:
function getNews(url) {
$.get(url, function (data) {
let commentsUrl = data.commentsUrl;
let url = 'http://localhost:3000' + commentsUrl;
sx.next(url);
})
}
function* sendXml(){
let url = yield getNews('http://localhost:3000/news?id=3');
yield getNews(url);
}
// 获取遍历器对象
let sx = sendXml();
sx.next();