Node.js, Synchronize.js and return values

1.9k Views Asked by At

I'm using this wonderful sync module, synchronize.js - http://alexeypetrushin.github.io/synchronize/docs/index.html.

I've run into a situation where I have to get the return value of the sync'd function into the scope outside of the fiber. Here's a basic example of what I'm talking about:

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

Whereas records would, in theory, contain the value of resultsfrom within the fiber scope. I've been reading up on futures (fibers/futures module) and how they might be used in this situation but I have yet to come up with anything close to working. I'd love some direction and/or a solution.

edit:

For a more thorough example of what I'm looking to accomplish:

  // 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;
}

As you can see here, what I'd like to accomplish is to get the value of results in the primary scope, from the fiber's scope.

2

There are 2 best solutions below

0
On

Now it does support it, use following form

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

It's not a scope problem. This wont work because return res; executes before the fiber returns. That is why it's undefined.

You need to rewrite your exec function to take a callback. Then you could use synchronize.js on the exec function itself.