据我了解 Javascript 生成器的当前规范,您必须明确标记包含 yield
的函数。
我想知道这背后的原因是什么。
如果这是真的,它会迫使人们写:
let thirdfunc = function*() {
let value = 5;
let other = yield 6;
return value;
};
let secondfunc = function*() {
yield thirdfunc();
};
let firstfunc = function*() {
yield secondfunc();
};
let gen = function*() {
// some code
// more code
yield firstfunc();
// and code
};
let it = gen();
while( !it.done() ) {
it.next();
};
这意味着,生成器会像代码库中的癌症一样扩散。 而最后,对于开发人员来说,只生成和处理迭代器真的很有趣。
我会发现它更实用,只需定义我想处理迭代的地方。
let thirdfunc = function() {
let value = 5;
let other = yield 6; // Change 1: incorporate yield
return value;
};
let secondfunc = function() {
thirdfunc();
};
let firstfunc = function() {
secondfunc();
};
let gen = function*() { // Change 2: at this level I want to deal with descendant yields
// some code
// more code
firstfunc();
// and code
};
// Change 3: Handle iterator
let it = gen();
while( !it.done() ) {
it.next();
}
如果浏览器随后必须转换 yield
调用和生成器处理程序之间的所有内容(firstfunc
、secondfunc
、thirdfunc
) 转换成promise/future 形式,这应该会自动工作,而不是 Javascript 开发人员的事。
或者是否真的有很好的理由不这样做?
最佳答案
我在 http://calculist.org/blog/2011/12/14/why-coroutines-wont-work-on-the-web/ 描述了设计这方面的基本原理- 简而言之,完整的协程(这就是你所描述的)干扰了 JavaScript 的运行到完成模型的精神,使得更难预测你的代码何时可以在类似于多线程语言的意义上被“抢占” Java、C# 和 C++。博客文章更详细地介绍了一些其他原因。
关于javascript - 发电机真的有侵入性吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17070779/