Im trying to fetch some data in dependecy of currently existing data. The usecase is the following: I have a json array of groups, to calculate the amount of all transactions of each group i have to do an axios.get request for each group (to request this groups i need there groupIds, existing in the groups array). But i think i stuck cause i dont really know how to iterate through a for loop asynchronously. Here is what i did:
repareTransactionAmouts: function(){
for(var i = 0; i < this.transactionGroups.length; i++){
var groupId = this.transactionGroups[i].groupId
this.transactionsGroupsCount = i;
Promise.all([this.calculateTransactionAmounts(groupId)]).then( promiseData => {
this.transactionGroups[this.transactionsGroupsCount].totalAmount=promiseData[0]
if(this.transactionsGroupsCount == this.transactionGroups.length){
this.transactionGroups.sort(this.GetSortOrder("totalAmount"))
this.amountsCalculated = true;
}
}
}
},
transactionsGroups is my array of filtered groups with transactions and transactionsGroupCount is a global variable to add the transactionamounts to the array position on [transactionsGroupCount]. When all groups are filled with the amout i want to sort this and set a boolean.
Next the function calculateTransactionAmounts:
calculateTransactionAmounts: function(groupId){
return new Promise((resolve, reject) => {
var transactions = []
var amount = null
axios
.get(webServiceURL + "/groups/" + groupId, {
headers: { Authorization: "0 " + this.authToken }
})
.then(response => {
transactions = response.data.payload.transactions;
console.log("Desired Group: " + JSON.stringify(response.data.payload));
for(let j = 0; j < transactions.length; j++){
amount += transactions[j].amount
console.log("Transactiongroup" )
console.log(JSON.stringify
(this.transactionGroups[this.transactionsGroupsCount]))
resolve(amount)
}
})
.catch(e => {
console.log("Errors get groupids: " + e);
reject(e)
});
})},
The main problem here is, that the for-loop is processed completly before the function calculateTransactionAmounts is called, so i have some calls but all with the same groupId. There is some fancy stuff happening which i cant explain why: The output "Desired Group" displays me every group i have in my array, but the "this.transactionGroups[this.transactionsGroupsCount]" outputs me allways the same group, for every iteration.
If it helps: im developing a vue2 app and need this fetched amount data to display some transaction charts