NodeBB Plugin - Changing a variable inside a function



  • 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.


  • Global Moderator

    @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 😉


 

| |

Looks like your connection to NodeBB was lost, please wait while we try to reconnect.