I am trying to create a promise chain in Angular to execute a series of queries:
for(variableIndex in _editableVariable.values) {
var v = _editableVariable.values[variableIndex];
if(v.value != v.old_value) {
console.log('v', v);
var newVariableRes = new VariableValueRes(v);
if(v.old_value == undefined) {
p.then(function() {
console.log('B', newVariableRes);
return newVariableRes.$save().$promise;
});
} else {
console.log('Try update: ', v);
p.then(function() {
console.log('C', newVariableRes);
return newVariableRes.$update().$promise;
});
}
}
}
However, I am encountering an issue when I output the console.log('v',v)
, which shows different value
for each variable.
Inside the promise, when I output the console.log('B', newVariableRes)
, the content of newVariableRes
is always the value
of the latest variable.
Example Output:
v
Object {value: "1", old_value: undefined, platform: "/api/v1/platform/1", product_variable: "/api/v1/product_var/2"}
v
Object {value: "2", old_value: undefined, platform: "/api/v1/platform/2", product_variable: "/api/v1/product_var/2"}
v
Object {value: "3", old_value: "", id: 7, platform: "/api/v1/platform/3", product_variable: "/api/v1/product_var/2"}
B
Resource {value: "3", old_value: "", id: 7, platform: "/api/v1/platform/3", product_variable: "/api/v1/product_var/2"…}
B
Resource {value: "3", old_value: "", id: 7, platform: "/api/v1/platform/3", product_variable: "/api/v1/product_var/2"…}
C
Resource {value: "3", old_value: "", id: 7, platform: "/api/v1/platform/3", product_variable: "/api/v1/product_var/2"…}
I am new to JavaScript and I believed that v
is a reference to the value. So, when I pass v
to VariableValueRes
, it should hold that reference. Changing the reference of
v</code should not affect the content of <code>VariableValueRes
.
Where could be the source of my misunderstanding?