Issue
I want to make multiple requests where the data appends the title with a number. But instead of e.g. "Hello 1", "Hello 2", "Hello 3", "Hello 4" I get "Hello 4", "Hello 4", "Hello 4", "Hello 4".
console.log(item.title);
shows "Hello 1", "Hello 2", "Hello 3", "Hello 4" correctly in the console.
I am guessing that it is because the request are asynchronous.
vm.title = vm.case.title;
for (let i = 1; i <= vm.number_of_cases_to_create; i++) {
vm.createNewCase(i, vm.case);
}
function createNewCase(number, item) {
item.title = vm.title + ' ' + number;
console.log(item.title);
CaseProvider.create(item).then(function (case) {
console.log(case.id);
});
}
Solution
You are right, that is an async consequence. On the line vm.createNewCase(i, vm.case)
you send the same object to the method createNewCase
and when async starts, it refers to the same object, so all calls use the same "Hello 4" value.
I propose to pass a copy of vm.case
to your method, then code sample should work as expected. There is a great answer about object cloning in javascript.
Answered By - Eugene
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.