代码之家  ›  专栏  ›  技术社区  ›  john doe

更好地理解javascript的产量

  •  3
  • john doe  · 技术社区  · 10 年前

    我的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服务器的响应,这是有意义的。但我不能完全理解这类函数的生成器的概念。有什么帮助吗?

    2 回复  |  直到 10 年前
        1
  •  3
  •   danneu    10 年前

    你不会屈服的 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')
    }
    
        2
  •  0
  •   255kb - Mockoon    10 年前

    根据 documentation . 其目的是返回要在下一次迭代中使用的迭代结果。

    如本例(取自文档)所示:

    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 }