JavaScript 中奇怪的 Yield 语法
我刚刚看了 Dave Herman 非常有趣的 task.js。在他的例子中,他有这样一行:
var [foo, bar] = yield join(read("foo.json"),
read("bar.json")).timeout(1000);
我熟悉生成器,但我不明白yield表达式如何计算为可以分配给[foo, bar]的东西。实际上,我没想到该表达式可以分配给任何东西,因为它基本上与 return 相同。
JS 的 Yield 语法似乎仍然缺乏文档,我找不到有关此的信息。
因此,为了澄清我的问题:最终分配给 foo 和 bar 的是什么?
I just took a look at Dave Herman's very interesting task.js. In his example he has this line:
var [foo, bar] = yield join(read("foo.json"),
read("bar.json")).timeout(1000);
I'm familiar with generators but I don't understand how the yield expression evaluates to something that can be assigned to [foo, bar]. I actually wouldn't have expected the expression to be assignable to anything since it is basically the same thing as return.
The yield syntax for JS still seems a bit underdocumented and I couldn't find info about this.
So to clarify my question: what ends up being assigned to foo and bar?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
实际上,相关段落位于 https://developer.mozilla.org/En/New_in_JavaScript_1.7:
我认为这仅在通过直接调用其方法来使用生成器而不是循环其值时才相关 - 循环将始终在生成器上调用
next()
并且从不send( )
。在某种程度上,生成器执行类似于协作多任务处理。生成器一直执行,直到找到
yield
语句。它将控制权返回给在生成器上调用next()
或send()
的人。然后调用者继续执行,直到执行下一个next()
或send()
调用 - 现在生成器再次执行。每个时间值都可以来回传递。这是一个简单的例子:
Actually, the relevant paragraph is a little below in https://developer.mozilla.org/En/New_in_JavaScript_1.7:
I think that this is only relevant if the generator is used by calling its methods directly, not when looping over its values - a loop will always call
next()
on the generator and neversend()
.In a way, generator execution is similar to cooperative multitasking. The generator executes until the
yield
statement is found. It returns control to whoever callednext()
orsend()
on the generator. The caller then continues executing, until the nextnext()
orsend()
call is performed - now the generator is executing again. Each time values can be passed back and forth.Here a simple example:
https://developer.mozilla.org/En/New_in_JavaScript_1.7
https://developer.mozilla.org/En/New_in_JavaScript_1.7