更好地理解javascript的收益率

时间:2015-02-24 07:24:41

标签: javascript generator koa

我的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"

现在,"确定"是redis服务器的响应,这是有道理的。但我无法完全掌握这类功能的发电机概念。有什么帮助吗?

2 个答案:

答案 0 :(得分:1)

您不会产生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')
}

答案 1 :(得分:0)

根据documentation,应该在生成器函数内使用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 }
相关问题