Wednesday 22 February 2017

node.js - Return json object from executed function in presenter method



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


Answer



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

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...