0

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? Commented Sep 2, 2013 at 14:49
  • instance defined in exec is not available in method create. I am trying get out variable to the method. Commented Sep 2, 2013 at 14:56

2 Answers 2

1

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.
    }
};
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for help. I am starting with async javascript and sometimes it is hard to go over know-how of standard synchronous programming.
Yes, don't feel bad about it. Everyone has a struggle to adjust to this. Asynchronous is just so fundamentally different from synchronous code. It takes a while before the light bulb finally lights up.
0

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]"
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.