javascript - Add new element in existing object -
i using node.js.
i have add new elements in object before send response client.
user.getmatch(req.user, function(err, match){ for( k=0; k<match.length; k++){ var userid = { id : match[k].match_id }; var user = new user(userid); console.log('k: ' + k); user.getuserinfo(function(err2, info){ console.log('k here: ' + k); if(info){ match[k].foo = info[0].foo; } }); } var response = { data : match }; res.json(response); }); i want add element "foo" user.getuserinfo object "match" returned user.getmatch. , send data response client.
but got error because "k" inside of user.getuserinfo not equal "k" outside. not know why both "k" not equal.
and how send response client after performing loop.
thanks help!
some problems here:
first, k not defined k you're using global variable not want. need define 'var k'.
second, callback function you're passing user.getuserinfo() (probably) executed @ unknown time in future. @ point loop for (k ... has finished the k variable has new value since value had when called user.getuserinfo(). , here's tricky part: code inside callback function use k's recent value. not use value k had when function created.
you can solve adding parameter callback function , binding k using .bind method:
user.getmatch(req.user, function(err, match){ var k; for(k=0; k < match.length; k++){ var userid = { id : match[k].match_id }; var user = new user(userid); console.log('k: ' + k); var callback = function(k, err2, info){ console.log('k here: ' + k); if(info){ match[k].foo = info[0].foo; } }.bind(null, k); user.getuserinfo(callback); } var response = { data: match }; res.json(response); }); also, you'd better off using .foreach iterating on array:
user.getmatch(req.user, function(err, match){ match.foreach(function(curr) { var userid = { id : curr.match_id }; var user = new user(userid); user.getuserinfo(function(err2, info){ if(info){ curr.foo = info[0].foo; } } }); var response = { data: match }; res.json(response); }); although array.foreach can give current index in iteration, no longer needed. use curr value (which gives current element in iteration).
finally, think code here send response before user.getuserinfo() calls have been executed. achieve need know when user.getuserinfo() have been completed. can achieved adding variable numleft decremented each time user info. when variable reaches 0 know getuserinfo() have completed , therefore safe send response back.
user.getmatch(req.user, function(err, match) { var numleft = match.length; match.foreach(function(curr) { var user = new user({ id : curr.match_id }); user.getuserinfo(function(err2, info){ if(info) { curr.foo = info[0].foo; } --numleft; if (numleft == 0) res.json({ data: match }); } }); });
Comments
Post a Comment