更好地理解 javascript 的产量
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服务器的响应,这是有道理的。但是我不能完全理解这种函数的生成器的概念。有帮助吗?
根据 documentation,Yield 应该在生成器函数中使用。
目的是return一次迭代的结果要在下一次迭代中使用。
就像这个例子(取自文档):
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 }
您不会屈服 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')
}
我的 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服务器的响应,这是有道理的。但是我不能完全理解这种函数的生成器的概念。有帮助吗?
根据 documentation,Yield 应该在生成器函数中使用。 目的是return一次迭代的结果要在下一次迭代中使用。
就像这个例子(取自文档):
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 }
您不会屈服 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')
}