0

I'm trying to handle loop with $.get that handle error with adding fail attempt to log.

var fileSuccess= [];
var fileFail= [];


  if (records.length > 0) {
        
    $.each(records, function(i,r){
        fileName= model.getValue(r,"NAME");
        folderName= model.getValue(r,"FOLDER");        
        
        var promise = $.get(url + folderName + "/" + fileName, function() {
            fileSuccess.push(folderName+ "/" + fileName);
            })
        .fail(function() {fileFail.push(fileName);});
        
     });  
    
    console.log(fileSuccess); 
    console.log(fileFail); // it shows array [] but with two objects 0:xxxx, 1:xxxx, length = 2
    console.log(fileFail.length); // it shows 0
      


};

Why fileFail array is losing all data?

  • It's hard for me to handle that questions, but I will try to use it. Little tip how to understand that? – Paweł Żurkiewicz Oct 02 '20 at 09:43
  • 1
    No worries, it's a little confusing. Essentially you're doing this: 1 start a request to set fileSuccess/fileFail 2 immediately check values 3 complete the request that sets the values - ie `$.get` is asynchronous so your `console.log`s are running before the results have come back from the server. The link above is only a first step in understanding this as you need to wait for *all* your requests to complete before checking the fileSuccess/fileFail – freedomn-m Oct 02 '20 at 09:55
  • I quite understand how to do it for 1,2 $.get but I don't know how to implement this with dynamic loop with undefined loops – Paweł Żurkiewicz Oct 02 '20 at 12:56
  • Here's one (relatively old) method: https://stackoverflow.com/a/4369592/2181514 but you probably want this one: https://stackoverflow.com/a/36705604/2181514 – freedomn-m Oct 02 '20 at 13:06
  • Ehhh It surpass me i think. I can't find out how to when it succes add to one list if no add to other, and I need to handle the response of $.get and add it to dfferent array – Paweł Żurkiewicz Oct 02 '20 at 13:23
  • Yes, I can see that. You might be better off making a *single* ajax call with your name/folder values in an array/collection then your $.when.done problems will go away as they'll only be one response. This will also help the load on your server as it will only have to handle a single call. – freedomn-m Oct 02 '20 at 13:28

0 Answers0