Reputation: 4182
My NodeJs code that uses request is as follows:
var objIdArr = [obj1, obj2, obj3];
var index = 0;
var result = {};
var resultArr = [];
(function deleteRecur(){
if (index > objIdArr.length-1) {
//we are done iterating
console.log(resultArr); //faulty resulte
} else
{
request( //nodejs request module
{
uri: base_uri + '/' + objIdArr[index],
method: 'DELETE',
headers: headers
},
function(error, response, body) {
var arg = (transMap.get(objType)).res[0];
if (!error && response.statusCode == 200) {
result['vmid'] = objIdArr[index];
result["result"] = "Success";
} else{
result['vmid'] = objIdArr[index];
result["result"] = "failure";
result["detail"] = error;
}
resultArr[index] = result;
index++;
deleteRecur();
});
}
}());
Expected resultArr [{ vmid: 'obj1', result: 'OK' },{ vmid: 'obj2', result: 'OK' },{ vmid: 'obj3', result: 'OK'}].
But console.log prints [{ vmid: 'obj3', result: 'OK' },{ vmid: 'obj3', result: 'OK' },{ vmid: 'obj3', result: 'OK'}].
Seems like whenever I change result elsewhere in the code, its affecting the array resultArr too. How is this possible? Isnt javascript supposed to be pass by value?
How do I resolve this?
Upvotes: 1
Views: 40
Reputation: 119031
Create var result = {};
inside the function where you use it and push it into resultArr
. Currently you are overwriting the data each time (the array contains the same object multiple times instead of multiple objects).
Upvotes: 2