Stone
Stone

Reputation: 749

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!

Upvotes: 0

Views: 767

Answers (2)

IAmDranged
IAmDranged

Reputation: 3020

Reading about the asynchronous and single threaded nature of javascript would help you understand what happens here.

Essentially the following instruction:

resultPromise.then(function(value) {
  usuario = value;
  // use value here before continues;
  console.log("first");
});

Is asking "Execute the callback function at some point in the future when the promise is resolved and execution stack is cleared". The callback function doesn't run in place, and actually won't run until after the current execution thread completes.

Upvotes: 0

guest271314
guest271314

Reputation: 1

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)
})

Upvotes: 1

Related Questions