[英]Better understanding javascript's yield
我的Koa应用中有以下代码:
exports.home = function *(next){
yield save('bar')
}
var save = function(what){
var response = redis.save('foo', what)
return response
}
但是我收到以下错误: TypeError: You may only yield a function, promise, generator, array, or object, but the following object was passed: "OK"
现在,“ ok”是来自redis服务器的响应,这很有意义。 但是我无法完全掌握此类功能的生成器概念。 有什么帮助吗?
您不会产生save('bar')
因为SAVE是同步的。 (确定要使用保存吗?)
由于它是同步的,因此您应该更改此设置:
exports.home = function *(next){
yield save('bar')
}
对此:
exports.home = function *(next){
save('bar')
}
它将阻止执行直到完成。
几乎所有其他Redis方法都是异步的,因此您需要yield
它们。
例如:
exports.home = function *(next){
var result = yield redis.set('foo', 'bar')
}
根据文档,应该在生成器函数内部使用yield。 目的是返回要在下一次迭代中使用的迭代结果。
像本示例一样(摘自文档):
function* foo(){
var index = 0;
while (index <= 2) // when index reaches 3,
// yield's done will be true
// and its value will be undefined;
yield index++;
}
var iterator = foo();
console.log(iterator.next()); // { value:0, done:false }
console.log(iterator.next()); // { value:1, done:false }
console.log(iterator.next()); // { value:2, done:false }
console.log(iterator.next()); // { value:undefined, done:true }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.