0
votes

I need load json object from anonymous function to variable instance.

In this example is instance undefined.

I am sure, the solution is simple, but newbie in node and no answer found...:(

module.exports = {
    create: function(req,res){
        instance = EngineInstance.findById(req.body.engineInstanceId).exec(function(err,instance){
            if (err) return res.send(err,500);
            if (!instance) return res.send("No engine instance found!", 404);
            return instance;
        });
        namespamce = instance.namespace;...
    }
};
2
why do you have two variables with same name instance? - vinayr
instance defined in exec is not available in method create. I am trying get out variable to the method. - podolinek

2 Answers

1
votes

You have a very common and fundamental misconception about how asynchronous code works. Full stop. Go read tutorials and do guided exercises. Asynchronous IO such as findById you have above uses CALLBACKS that invoke functions with result variables. It does not use RETURN VALUES because they are useless due to the order in which asynchronous code executes.

module.exports = {
    create: function(req,res){
        instance = EngineInstance.findById(req.body.engineInstanceId).exec(function(err,instance){
            if (err) return res.send(err,500);
            if (!instance) return res.send("No engine instance found!", 404);
            //it is useless to return a value from this anonymous async callback
            //nothing will receive it. It will be ignored.
            //probably something like this is what you need
            req.namespamce = instance.namespace;
        });
        //do NOT put code here that needs req.namespace. This code runs BEFORE
        //the `findById` I/O callback runs.
    }
};
0
votes

Changed the MYSQL query to query multiple things together instead of isolating the query for accessPoint and the added this code:

results[0].accessPoint = JSON.parse(results[0].accessPoint)
res.send(results[0]);

Now I get this back and its exactly what I wanted:

"accessPoint": {
    "mode": "client",
    "rate": 0,
    "ssid": "RMG",
    "signal": 0,
    "channel": 0,
    "password": "",
    "username": "[email protected]"
  }