我听说过JavaScript中的“yield”关键字,但我发现关于它的文档非常糟糕。有人能给我解释一下(或者推荐一个解释它的网站)它的用法和用途吗?
当前回答
异步javascript调用之间的依赖关系。
另一个关于如何使用yield的好例子。
函数请求(url) { Axios.get (url).then((response) => { it.next(响应); }) } 函数* main() { Const result1 = yield request('http://some.api.com'); Const result2 = yield request('http://some.otherapi?Id =' + result1。id); console.log('您的响应是:' + result2.value); } Var it = main(); it.next ()
其他回答
它用于迭代器生成器。基本上,它允许您使用过程代码制作(可能是无限的)序列。请参阅Mozilla的文档。
异步javascript调用之间的依赖关系。
另一个关于如何使用yield的好例子。
函数请求(url) { Axios.get (url).then((response) => { it.next(响应); }) } 函数* main() { Const result1 = yield request('http://some.api.com'); Const result2 = yield request('http://some.otherapi?Id =' + result1。id); console.log('您的响应是:' + result2.value); } Var it = main(); it.next ()
不要忘记使用非常有用的“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);
}
使用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 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());
推荐文章
- 将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标签?