更好地理解javascript's产量

Better understanding javascript's yield

本文关键字:产量 javascript 更好      更新时间:2024-05-07

我的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是同步的,所以不会产生save('bar')。(您确定要使用保存吗?)

由于它是同步的,您应该更改它:

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 }