Liam Hogan
Liam Hogan

Reputation: 334

Array.push is not working with objects in Nodejs

How can I add an object as an entry to an array, like I'm trying to do here...

 displayAccounts(function(data){
    var index;
    var accs = new Array();
    for (index = 0; index < data.length; ++index) {
      rclient.get(data.account, function (info) {
        accs.push({
            account: data.account,
            info: info
          });
      });
    }
    console.log(accs);
  });

Output:

accs = []

Desired solution:

accs = [{account: 'jak', info: 0},{account: 'jil', info: 1}]

Upvotes: 0

Views: 3546

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074038

The problem is almost certainly that rclient.get is asynchronous, so examining the array after your loop is examining it too soon (the gets have been started, but they haven't finished yet); it will get filled in by callbacks that occur asynchronously. Wait until the last callback has occurred, e.g.:

displayAccounts(function(data){
    var index;
    var accs = []; // [] is a better way to write new Array()
    for (index = 0; index < data.length; ++index) 
        rclient.get(data.account, function (info) {
            accs.push({
                account: data.account,
                info: info
            });
            if (accs.length === data.length) {
                // We're done, *now* look at / use the array
                console.log(accs);
            }
        });
    }
});

Note that depending on how rclient.get works, the callbacks may or may not occur in the same order as the requests.


Side note: That rclient.get(data.account, ... looks suspicious, you're repeatedly requesting the same information. Perhaps rclient.get(data[index].account, ...?

Upvotes: 6

Related Questions