0

I did solve the problem with this post:How to take an action when all ajax calls in each loop success? . So at the end I counted how many times I have to launch the request, than I have variable inside which decreases each time and when it hits 0 I launch the function. This way my problem is solved. Probably this question is a duplicate of How to take an action when all ajax calls in each loop success? this since this kinda answers the question. Let me check and than I don't know, maybe I'll remove my question. I run same function with different url ajax requests with loop and I want a way to make sure I continue code only after the function returns all the data and only after continues the code. With while I can only check if function was sent one time and forwarded the result I want to make sure the function was run multiple times and I got response for each of the requests. Is this a duplicate? If I run my function with an AJAX request I can use when to make sure the result was forwarded and only afterwards run the next code.

However if I run the function multiple times with different URLs each time then I can't make sure that all the requests are finished and I don't know how to check.

 var somearray['test','car','menu'];
var array=[];
function test(thislink){
return $.ajax({
  type: "GET",
   url:"http://somewhere"+thislink,

  success: function(response)
  {



    array.push(response);
  }
});

}

for(i=0; i<somearray;i++){
test(somearray[i]);

}

$.when(test()).then(function( ) {
//so first request would run.
console.log(array[0]); //would return something

//while array[1] and higher may return undefined.

console.log(array[1]); // undefined. I rad that I have to use $.when.apply but I don't understand how to do that.
} ); 
    //if i do that when will only make sure first request is success but if I try to get other url's requests probably they will be undefined.
Mikheil misha
  • 51
  • 1
  • 6

1 Answers1

0

If you're familiar with Promises, you can use Promise.all(). It checks that all promises are "good" and returns the value you pass, otherwise if for example in 2 of them a error is caught, it jumps to the catch statement.

corrado4eyes
  • 283
  • 2
  • 11
  • I'll check that and let you know. – Mikheil misha Jul 04 '19 at 09:23
  • It seems that it doesn't work. So all I do is that I run function multiple time with different url and I don't know how to check that all multiple function run forwarded results. Maybe I have to put each function call inside array and check them than? Well, I don't know, I tried and something not going well. – Mikheil misha Jul 04 '19 at 09:45
  • Try to follow this [example](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all) – corrado4eyes Jul 04 '19 at 10:40