我听说过JavaScript中的“yield”关键字,但我发现关于它的文档非常糟糕。有人能给我解释一下(或者推荐一个解释它的网站)它的用法和用途吗?
当前回答
使用yield关键字的斐波那契序列生成器。
function* fibonacci() {
var a = -1, b = 1, c;
while(1) {
c = a + b;
a = b;
b = c;
yield c;
}
}
var fibonacciGenerator = fibonacci();
fibonacciGenerator.next().value; // 0
fibonacciGenerator.next().value; // 1
fibonacciGenerator.next().value; // 1
fibonacciGenerator.next().value; // 2
其他回答
这真的很简单,它是这样工作的
Yield关键字只是帮助在任何时间异步暂停和恢复一个函数。 此外,它还有助于从生成器函数返回值。
以这个简单的生成器函数为例:
function* process() {
console.log('Start process 1');
console.log('Pause process2 until call next()');
yield;
console.log('Resumed process2');
console.log('Pause process3 until call next()');
let parms = yield {age: 12};
console.log("Passed by final process next(90): " + parms);
console.log('Resumed process3');
console.log('End of the process function');
}
Let _process = process();
在调用_process.next()之前,它不会执行前两行代码,然后第一个yield将暂停函数。 要继续该函数直到下一个暂停点(yield关键字),需要调用_process.next()。
您可以将多个yield看作是javascript调试器中单个函数中的断点。直到 你告诉导航下一个断点,它不会执行代码 块。(注意:不阻塞整个应用程序)
但是当yield执行暂停和恢复行为时,它也可以返回一些结果{value: any, done: boolean} 根据前面的函数,我们没有输出任何值。如果我们查看之前的输出,它将显示相同的{value: undefined, done: false} 值未定义。
让我们深入研究yield关键字。可选地,您可以添加表达式和设置分配一个默认可选值。(官方文档语法)
[rv] = yield [expression];
表达式:从生成器函数返回的值
yield any;
yield {age: 12};
rv:返回传递给生成器next()方法的可选值
简单地,您可以使用这种机制将参数传递给process()函数,以执行不同的yield部分。
let val = yield 99;
_process.next(10);
now the val will be 10
现在就试试
用法
懒惰的评价 无限的序列 异步控制流
引用:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/yield http://javascript.tutorialhorizon.com/2015/09/16/generators-and-yield-in-es6/ https://strongloop.com/strongblog/how-to-generators-node-js-yield-use-cases/
Yield还可以使用协程框架来消除回调地狱。
function start(routine, data) {
result = routine.next(data);
if(!result.done) {
result.value(function(err, data) {
if(err) routine.throw(err); // continue next iteration of routine with an exception
else start(routine, data); // continue next iteration of routine normally
});
}
}
// with nodejs as 'node --harmony'
fs = require('fs');
function read(path) {
return function(callback) { fs.readFile(path, {encoding:'utf8'}, callback); };
}
function* routine() {
text = yield read('/path/to/some/file.txt');
console.log(text);
}
// with mdn javascript 1.7
http.get = function(url) {
return function(callback) {
// make xhr request object,
// use callback(null, resonseText) on status 200,
// or callback(responseText) on status 500
};
};
function* routine() {
text = yield http.get('/path/to/some/file.txt');
console.log(text);
}
// invoked as.., on both mdn and nodejs
start(routine());
给出一个完整的答案:yield的工作原理类似于return,但在发电机中。
对于通常给出的例子,其工作原理如下:
function *squareGen(x) {
var i;
for (i = 0; i < x; i++) {
yield i*i;
}
}
var gen = squareGen(3);
console.log(gen.next().value); // prints 0
console.log(gen.next().value); // prints 1
console.log(gen.next().value); // prints 4
但是yield关键字还有第二个用途。它可以用来向生成器发送值。
为了澄清,举个小例子:
function *sendStuff() {
y = yield (0);
yield y*y;
}
var gen = sendStuff();
console.log(gen.next().value); // prints 0
console.log(gen.next(2).value); // prints 4
它的工作原理是,将值2赋给y,在它停止在第一个yield(返回0)后将其发送给生成器。
这使我们能够看到一些非常时髦的东西。(查协程)
不要忘记使用非常有用的“x of generator”语法来遍历生成器。根本不需要使用next()函数。
function* square(x){
for(i=0;i<100;i++){
x = x * 2;
yield x;
}
}
var gen = square(2);
for(x of gen){
console.log(x);
}
迟回答,也许现在每个人都知道收益率,但一些更好的文件已经出现。
将James Long的《Javascript的未来:生成器》中的一个例子改编为官方的Harmony标准:
function * foo(x) {
while (true) {
x = x * 2;
yield x;
}
}
当你调用foo时,你会得到一个Generator对象,它有一个next 方法。”
var g = foo(2);
g.next(); // -> 4
g.next(); // -> 8
g.next(); // -> 16
收益率有点像回报,你会得到一些回报。Return x返回x的值,但yield x返回一个函数,它为您提供了一个迭代到下一个值的方法。如果您有一个潜在的内存密集型过程,您可能希望在迭代期间中断这个过程,那么这个方法很有用。
推荐文章
- 将lodash导入到angular + typescript应用程序中
- 什么时候使用setAttribute vs .attribute=在JavaScript?
- 每60秒调用一个函数
- 我如何上传一个文件与JS获取API?
- 在JavaScript中是否有一个“not in”操作符来检查对象属性?
- 我如何能得到滚动条的位置与JavaScript?
- JavaScript中的yield关键字是什么?
- 如何显示一个对象的所有方法?
- .js和.mjs文件有什么区别?
- Axios处理错误
- ESLint解析错误:意外的令牌
- 同时映射和过滤一个数组
- TypeScript:创建一个空的类型容器数组
- 在JavaScript中将大字符串分割为n大小的块
- 如何从JavaScript字符串中剥离HTML标签?