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:

    1. User.getUserField gets called
    2. Second console.log(user_data.email); gets executed
    3. 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.

  • Thank you, I always liked Christmas tree styling 😉


Suggested Topics


  • 0 Votes
    22 Posts
    927 Views
  • 0 Votes
    11 Posts
    552 Views
  • 0 Votes
    2 Posts
    972 Views
  • 0 Votes
    1 Posts
    1175 Views
  • 0 Votes
    3 Posts
    2707 Views