Search code examples
node.jssynchronize

passing nodejs asynblock data


here is my code.

exports.connect = function(){
    var that = null;
    var client = new mongo.Db(ih.cfg.db.name, new mongo.Server(ih.cfg.db.host, ih.cfg.db.port, {auto_reconnect: true}));

    asyncblock(function(flow){
        client.open(flow.add('db'));
        var db = flow.wait('db');
        that = db;
    });

    return that
}

i'm using asynblock to synchronize my code, problem is i cannot get db into 'that'. any suggestion? thanks.


Solution

  • The problem is that your connect function returns immediately before the function passed for asyncblock runs - because your callback passed to asyncblock is called asynchronously. It can synchronize your code only in these callback functions passed to asyncblock.

    The solution can be to call asyncblock outside, and pass the flow object to this module.

    Eg.: main file:

    var connect = require("./connect.js") // the file with your code in your question
    , asyncblock = require("asyncblock");
    
    asyncblock(function(flow)) {
      db = connect(flow);
      // rest of your code using db connection
    }
    

    connect.js:

    exports.connect = function(flow){
        var client = new mongo.Db(ih.cfg.db.name, new mongo.Server(ih.cfg.db.host, ih.cfg.db.port, {auto_reconnect: true}));
        client.open(flow.add('db'));
        var db = flow.wait('db');
        return db
    }