问题
I tried all the solutions posted here, but nothing worked, because my problem is a bit different.
I have the following code (calls on a code from external neo4j module to insert a node into Neo4J database and then gets the Neo4J Id of that node):
dbneo.insertNode({
auth_id: user.id,
username: user.name,
name: user.name
},function (err, node){
if(err) throw err;
// Output node properties.
console.log(node.data);
// Output node id.
console.log(node.id);
});
All works fine, but how do I deliver node.id outside of the scope of function (err,node) to then add this value to another object?
When I try to do something like
user.neo_id = node.id;
after that block of the code above, it's undefined (of course).
Tried to run the dbneo.insertNode inside a named function, but if I put the return value into function (err, node) it's undefined anyway.
Sorry if the question is a bit simple/stupid, but I'm just starting in JavaScript. Thank you!
回答1:
Ok, so after your advice, I have this interim code. Probably not the best (may clog), but it resolves the problem.
I simply call for the next function only after I'm sure I received the variable (node.id) from Neo4J database. If anyone knows a more elegant solution, please, do let me know (especially with async library).
dbneo.insertNode({
auth_id: user.id,
username: user.name,
name: user.name
},function (err, node){
if(err) throw err;
// Output node properties.
console.log(node.data);
// Output node id.
console.log(node.id);
// RECEIVED node.id ? ONLY THEN SEND IT TO THE FUNCTION THAT NEEDS IT
send_neo_id(node.id);
});
// THIS IS THE FUNCTION THAT WAS NOT RECEIVING NODE.ID BEFORE:
function send_neo_id(neo_id) {
user.neo_id = neo_id;
db.set('user:id:' + user.name, id, function(err) {
if (err) return fn(err);
db.hmset('user:' + id, user, function(err) {
fn(err);
});
});
};
来源:https://stackoverflow.com/questions/21581255/return-variable-outside-of-a-function-scope-in-javascript