jk2K
jk2K

Reputation: 4517

javascript variable not updating in node

rows is array, row is object, I want to add a property to row; I tried the following:

rows.forEach(function(row) {
    User.find(row.owner).success(function(user) {
        row.ownername = user.username;
    });
});
console.dir(rows);

but rows not joined ownername property, output is still [], i am I missing something? Any help is appreciated.

sorry, I said is not clear, rows is array, such as:

[{"id":19427,"name":"data1","owner":123},
{"id":19427,"name":"data2","owner":123},
{"id":19427,"name":"data3","owner":123},
{"id":19427,"name":"data4","owner":123}]

row represent a element of rows, such as

{"id":19427,"name":"data2","owner":123}

I just want to add a property to row, finally rows like

[{"id":19427,"name":"data1","owner":123,"ownername":"a"},
{"id":19427,"name":"data2","owner":123,"ownername":"ab"},
{"id":19427,"name":"data3","owner":123,"ownername":"abc"},
{"id":19427,"name":"data4","owner":123,"ownername":"abcd"}]

Upvotes: 1

Views: 369

Answers (1)

Paul
Paul

Reputation: 27423

Node.js is asynchronous.

There is no guarantee that console.dir(rows) executes before or after User.find(...).success(...) updates the rows variable.

As a practical matter, suppose User.find() consults a database or disk file and it takes, say, 200ms or 1/5 of a second to get an answer. That may as well be forever. Node is queuing all these requests for Users information in the for loop. In the code originally posted, immediately after sending these requests it sends the current value of the row variable to the console. But that's too soon. It needs to wait.

If console.dir executes before User.find(...).success(...), then the program will print the unmodified value of rows.

User.find(...).success(...) only sets up a potential for the rows to be updated at some unknown point in the future. This code should normally be interpreted as "find the user and when the user is found, execute the success function".

Furthermore, I have no idea if the call to User... is correct or sufficient to execute a query on this User api or backend or if there might be a bug in that code.

Try this and see if it yields something more sensible:

rows.forEach(function(row) {
    User.find(row.owner).success(function(user) {
       console.log("changing row.ownername from "+row.ownername); 
       row.ownername = user.username;
       console.log("to "+user.username+" -- result "+row.ownername);

    });
});
console.dir(rows);
setTimeout(function(){ console.dir(rows); }, 10000); // 10 sec delay

Upvotes: 1

Related Questions