ybogdanov / node-sync

Write simple and readable synchronous code in nodejs using fibers
MIT License
492 stars 70 forks source link

I want to write a function which has a return value. How to do? #39

Open qt911025 opened 9 years ago

qt911025 commented 9 years ago

The function contains a synchronized process.Such as

// A getter method
var getData;
Sync(function(){//But it doe's not work.
  getData = function(path){
    var cacheDoc = cache.get(this.id);//"cache" is a "node-cache"
    if(!cacheDoc || cacheDoc[path] === undefined){
      cacheDoc = statics.findById.sync(this,this.id,cachedPathsStr);//mongoose findById
    }
    return cacheDoc[path];
  };
});

The code above will not work because of the fiber cannot be detected.

I also tried other way.

// A getter method
var getData = function(path){
  Sync(function(){
      var cacheDoc = cache.get(this.id);//"cache" is a "node-cache"
      if(!cacheDoc || cacheDoc[path] === undefined){
        cacheDoc = statics.findById.sync(this,this.id,cachedPathsStr);//mongoose findById
      }
  });
  return cacheDoc[path];
};

The execution will jump to the "return" statement unless the "return" is contained in the "Sync". I have to put the whole function into it, and put the code which call this method. I can't export the module if I put module.export = moduleObj into the "Sync" capsule, because of the same problem: Error: yield() called with no fiber running

sa-0001 commented 9 years ago

defining the function inside a fiber, or calling sync() within the function definition don't do what you think they will - you need to simply call the function from within a fiber:

var getData = function(path){
    var cacheDoc = cache.get(this.id);//"cache" is a "node-cache"
    if(!cacheDoc || cacheDoc[path] === undefined){
      cacheDoc = statics.findById.sync(this,this.id,cachedPathsStr);//mongoose findById
    }
    return cacheDoc[path];
};

sync(function(){
  console.log(getData());
});

also, cacheDoc would not be available to return if it is defined within a function.