(100分) 为什么yield和next的数目不匹配

bsnry 2017-10-09 06:05:31
这个例子中的next有什么作用?

代码中只有2个yield, 但是例子中有3个next,

我们看第三个next,也就是:


function getTpl(tpl){
console.log("getTpl----" + tpl);
console.log(tpl);
setTimeout(function(){
iterator.next('hello ${name}')
}, 3000)
}

这个next 有什么作用? 为什么yield和next的数目不匹配? 我所知道的,

next有个作用,可以把自己的参数返回给 yield表达式左边的变量,还能执行代码到下一个yield。

可是数目不匹配啊。第一个next的参数是空的。


// 异步任务模型
function getData(src){
console.log("getData---" + src);
setTimeout(function(){
iterator.next({tpl: 'tpl.html', name: 'fsjohnhuang'}) //第二个
}, 1000)
}

function getTpl(tpl){
console.log("getTpl----" + tpl);
console.log(tpl);
setTimeout(function(){
iterator.next('hello ${name}') //第三个
}, 3000)
}

function render(data, tpl){
console.log("--------render-----")
console.log(data, tpl);
return tpl.replace(/\$\{(\w+)\}/, function(){
return data[arguments[1]] == void 0 ? arguments[0] : data[arguments[1]]
})
}

// 主逻辑
function *getAritcles(src){
console.log('begin')
var data = yield getData(src)
var tpl = yield getTpl(data.tpl)
var res = render(data, tpl)
console.log("------getAritcles-----")
console.log(data);
console.log("-----end-----:res:" + res)

}

var iterator = getAritcles('dummy.json')
iterator.next() //第一个
...全文
217 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
似梦飞花 2017-10-09
  • 打赏
  • 举报
回复
第一个next走到第一个yield的右边 第二个next从第一个yield的左边开始一直走到下一个yield或者结束 其中yield左边可以有=赋值给一个变量 这就是第二个next的=传入的参数 你看 一个yield有两个next了 一个负责右边 一个负责左边 同理 两个yield需要三个next 可以自己找书看看
似梦飞花 2017-10-09
  • 打赏
  • 举报
回复
es6入门标准 你不知道的js 中卷 自己看下
functionsub 2017-10-09
  • 打赏
  • 举报
回复
es6的遍历器,自己查下相关资料吧。

87,921

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧