NodeBB Plugin - Changing a variable inside a function
Solved
Technical Support
-
Hi,
Started working on a plugin - but hit a bump
I am trying to change the value of a variable, as follows:
var user_data = { email: "N/A" }; User.getUserField(uid, 'email', function(err, email) { user_data.email=email; console.log(user_data.email); }); console.log(user_data.email);
The first printout shows the correct email, but the second one reverts back to "N/A".
I did pass user_data "by reference", that is I did not change user_data itself but its content (email field).Any idea what I am doing wrong?
Thank you!
JJ. -
@jjsagan the function
User.getUserField
is asynchronous, meaning that it doesn't execute in order with the rest of the code. It takes a callback function for that reason. What is really happening here is this:User.getUserField
gets called- Second
console.log(user_data.email);
gets executed - The callback function including the first
console.log(user_data.email);
gets executed
So you need to add anything that depends on changes you make inside the
User.getUserField
callback inside the callback.
Copyright © 2024 NodeBB | Contributors