I have arrays like below.
var clients = ['a','b'];
var reports = ['x','y','z'];
var finalData = [];
Now i need looping like this.
for(var i=0;i<reports.length;i++){
var response = {report : reports[i]}
for(var j=0;j<clients;j++){
response.client = clients[i];
$.ajax({
url :url,
success : function(data){
response.data = data;
finalData.push(response);
})
});
}
}
As ajax is asynchronous so it does not work properly. Also I need to wrap this up into react.js componentDidMount function and push the finalData into the state.
I tried $.each
instead of for loop and .bind(this)
to push the finaldata into the state. but i didnt get the correct data. I heard for async calls closure should be used but not getting how will that be implemented here.
The output i am looking for is.
finalData = [
{client:a,report:x,data : 'xyz'},
{client:b,report:x,data : 'xyz'},
{client:a,report:y,data : 'xyz'},
{client:b,report:y,data : 'xyz'},
{client:a,report:z,data : 'xyz'},
{client:b,report:z,data : 'xyz'}
]