Sunday, 13 January 2019

javascript - Call ajax inside loop using promise



Hi everyone I am trying to use ajax inside a loop using promise, but my second ajax call inside the loop don't way for the ajax request and continue the execution.



This is my code:



  var general = [];

var all_info =[];
var usuario =[];
var resultPromise = getProjects(); // Promise for a response.
resultPromise.then(function(all_projects) {
return $.when.apply($, all_projects.map(function (current_project, index){
var items = {};
items.name = current_project.key;
items.children = [{"total_cpu": current_project.cpuhour_tot, "num_jobs" : current_project.num_jobs }];
return addUsers(current_project.key)
.then(function(item_user) {

info_user = {};
info_user.name = item_user.key;
info_user.children = [{"total_cpu" : item_user.cpuhour_tot, "num_jobs": item_user.num_jobs }];
all_info.push(info_user);
});
items.children.push(all_info);
general.push(items)
}));
})
.then(function() {

console.log("complete", general);
})
.fail(function(jqxhr, textStatus, errorThrown) {
console.log(errorThrown);
})


when I return from this line return addUsers... I need to include the all_info values to items and before to execute other loop to all_projects I have to do that general.push(items)



but it is impossible to access to items.




What I am missing?



Thanks in advance!


Answer



Substitute .map() for .forEach() use $.when(), Function.prototype.apply(). usuario is an array; .push() value to the array.



resultPromise.then(function(all_projects) {
return $.when.apply($, all_projects.map(function (current_project, index){
var items = {};

items.name = current_project.key;
items.children = [{"total_cpu": current_project.cpuhour_tot, "num_jobs" : current_project.num_jobs }];
return addUsers(current_project.key)
.then(function(value) {
console.log(value)
usuario.push(value);
// use value here before continues;
// do stuff with `value` or `usuario` here
});
}));

})
.then(function() {
console.log("complete", usuario)
})
.fail(function(jqxhr, textStatus, errorThrown) {
console.log(errorThrown)
})

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...