简体   繁体   English

如何在javascript中模拟生成器的同步调用?

[英]How can I emulate a synchronous call with generators in javascript?

Suppose the next piece of code: 假设下一段代码:

var co = require('co');

var myObj = {
    getFieldValue: function() {
        var self = this;
        console.log(JSON.stringify(self));
        if (!self.fieldValue) {
            return function(cb) {
                // Emulate an async database load
                setTimeout(function() {
                    self.fieldValue = "the value from the database\n";
                    cb(null, self.fiedValue);
                }, 5000);
            };
        } else {
             return function(cb) {
                cb(null, self.fieldValue);
            };
        }
    },
};

co(function *() {
    var v1 = yield myObj.getFieldValue();
    console.log(v1);
    var v2 = yield myObj.getFieldValue();
    console.log(v2);
});

As you can see, I define myObj with a single method getFieldValue . 如您所见,我使用单个方法getFieldValue定义myObj The first time this methods is called, it loads the value from the database. 第一次调用此方法时,它将从数据库中加载值。 The value is cached and, in subsequent calls, it returns the value directly. 该值将被缓存,并在随后的调用中直接返回该值。 The solution works great, but the user of the object must run in a generator context and write a yield in front of each access to the object methods. 该解决方案效果很好,但是对象的用户必须在生成器上下文中运行,并在每次访问对象方法之前写一个yield。

I can assume that all calls will be done in a generator context. 我可以假设所有调用都将在生成器上下文中完成。 But is there a way to rewrite the myObj implementation so that the user does not need to include the yield keyword? 但是,有没有一种方法可以重写myObj实现,以便用户不需要包含yield关键字?

I would like the user could write some thing like this (without the yields): 我希望用户可以这样写(没有收益):

co(function *() {
    var v1 = myObj.getFieldValue();
    console.log(v1);
    var v2 = myObj.getFieldValue();
    console.log(v2);
});

If it helps, I recently took the first release of the rogue written for UNIX in C and rewrote it for javascript to work in a browser. 如果有帮助,我最近拿出了用C语言为UNIX编写的流氓程序的第一个版本,并将其重写了以使javascript在浏览器中工作。 I used a technic called continuation to be able to wait for key entry by the user because in javascript the are no interrupts. 我使用一种称为延续的技术来等待用户输入密钥,因为在javascript中没有中断。

So I would have a piece of C code like this: 所以我会有一段这样的C代码:

void function f() {

  // ... first part

  ch = getchar();

  // ... second part

}

that would be transformed in 那将被转化为

function f(f_higher_cont) {

  // ... first part

  var ch = getchar(f_cont1);

  return;
  // the execution stops here 

  function f_cont1 () {

    // ... second part
    f_higher_cont();
  }
}

the continuation is then stored to be reuse on a keypressed event. 然后继续存储以在按键事件中重用。 With closures everything would be restarted where it stoped. 使用闭包,一切将在停止的地方重新开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM