1

I am using promises in javascript and for the resolve variable I am passing a multidimensional array. But for some reason my array changes in the then function. Here is my code,

Id_name_disp = [[], []];
var list = $("#Approversdisp").val().split(", ");
var promise = new Promise(function(resolve, reject){
  for(var i = 0; i < list.length-1; i++){
    $.ajax({
      "url" :"private",
      "type" : "GET",
      "data" : {"name": list[i].trim()},
      "contentType" : "application/json",
      "success" : function(data) {
        Id_name_disp[0] = Id_name_disp[0].concat(data[0]);
        Id_name_disp[1] = Id_name_disp[1].concat(data[1]);
        resolve(Id_name_disp);
      },
      "error" : function(jqXHR, textStatus, errorThrown)
      {
        reject(textStatus+": "+jqXHR.responseText);
      }
    });
  }
});
promise.then(function(fromresolve){
  console.log(fromresolve);
  console.log(fromresolve[0]);
  console.log(fromresolve);
  console.log(fromresolve[0].length);
  for(var k = 0; k < list.length-1; k++){
    var ind = -1;
    for(var x = 0; x < fromresolve[0].length; x++){
      console.log("x: "+x);
      console.log(fromresolve[0][x]+" "+list[k]);
      ind = fromresolve[0][x].indexOf(list[k]);
      console.log(ind);
      if(ind > -1){
        console.log("found: "+ind);
        break;
      }
    }
    sapid+=" "+fromresolve[0][ind].substring(fromresolve[0][ind].indexOf("("), fromresolve[0][ind].indexOf(")")+1)+",";
    console.log(sapid);
  }
}).catch(function(fromreject){
  alert(fromreject);
});

fromresolve is multidimensional array where the 0 position is an array of 6 elements and 1st position is an array of 6 elements. but when I do fromresolve[0] I get an array with one element. Why is that happening. The expected result is fromresolve[0] will be an array of 6 elements.

some
  • 48,070
  • 14
  • 77
  • 93
kingofjong
  • 175
  • 2
  • 14
  • Why would you wrap `ajax` in `promise`, when `ajax` itself is a promise. May be you need to think differently. Instead of looping you could have used `Promise.all` on array of `ajax` API pushed in a variable. – NiRUS Sep 16 '19 at 19:55
  • 1
    There are a lot of unknowns in your code. You should know that your promise will resolve after the first ajax request returns and ignore the rest, since you have only one `resolve` call. Take a look at [Wait until all jQuery Ajax requests are done?](https://stackoverflow.com/q/3709597/215552) for information on how to wait until all of them are done. – Heretic Monkey Sep 16 '19 at 20:06
  • Avoid the [`Promise` constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it), and instead use `Promise.all` to wait for multiple concurrent ajax requests. – Bergi Sep 16 '19 at 20:11

0 Answers0