2014-01-19 40 views
3

我正在使用这个美妙的同步模块synchronize.js - http://alexeypetrushin.github.io/synchronize/docs/index.htmlNode.js,Synchronize.js和返回值

我遇到了一种情况,我必须将sync'd函数的返回值放入光纤以外的范围。下面是我在谈论的一个基本的例子:

var records = sync.fiber(function() { 
    var results = ... // some synchronized function 
    return results; 
}); 

records会,从理论上讲,含有纤维范围内的results值。我一直在阅读期货(纤维/期货模块)以及它们如何在这种情况下使用,但我还没有想出任何接近工作的东西。我喜欢一些方向和/或解决方案。

编辑:

对于我在寻找什么来完成更彻底的例子:

// executes a stored procedure/function 
exec: function (statement, parameters) { 

    init(); 

    var request = new sql.Request(), 
     results; 

    processParams(parameters, request); 

    var res = sync.fiber(function(){ 

     try { 
      var result = sync.await(request.execute(statement, sync.defers('recordsets', 'returnValue'))); 

      results = result.recordsets.length > 0 ? result.recordsets[0] : []; 

      return results; 
     } 
     catch (e) { 
      console.log('error:connection:exec(): ' + e); 
      throw(e); 
     } 

    }); 

    // though typical scope rules would mean that `results` has a 
    // value here, it's actually undefined. 

    // in theory, `res` would contain the return value from the `sync.fiber` callback 
    // which is our result set. 
    return res; 
} 

正如你可以看到这里,我想做到的是得到的值从光纤的范围来看,主要范围为results

回答

0

这不是范围问题。这不会工作,因为return res;在光纤返回之前执行。这就是为什么它是undefined

您需要重写您的exec函数才能进行回调。然后你可以在exec函数本身上使用synchronize.js。

2

现在不支持,就用下面的表格

var records = sync.fiber(function() { 
    var results = ... // some synchronized function 
    return results; 
}, function(err, results){... /* do something with results */});