rosiana rosiana - 2 months ago 5
Javascript Question

Javascript - Using promise for post PHP, get undefined result

I'm a newbie in JS and have a little to no knowledge about asynchronous program and promise. I have a problem in getting result from post PHP as written in this code:

showModalLink = function(d, i) {
$('#myModalLabel').text(d.source.name + ' - ' + d.target.name);
$('#modalJum').text(d.jumlahlelangsama);
var lelang = d.daftarlelangsama.split(", ");
var lelangmodal = [];
var promises = [];
for (var i = 0; i < lelang.length; i++) {
querystring = "select pemenang from lelang where id = " + lelang[i];
console.log(querystring);
var queryobj = {
query: querystring
};
promises.push($.post('indikasi3modal.php', queryobj));
}
Promise.all(promises).then(function(results) {
if (results[i] == d.source.name) {
console.log("1");
lelangmodal.push(lelang[i] + " - dimenangkan oleh " + d.source.name);
console.log(lelangmodal);
}
else if (results[i] == d.target.name) {
console.log("2");
lelangmodal.push(lelang[i] + " - dimenangkan oleh " + d.target.name);
console.log(lelangmodal);
}
else {
console.log("3");
lelangmodal.push(lelang[i]);
console.log(lelangmodal);
}
$('#modalLelang').text(lelangmodal);
$('#myModal').modal('show');
});}


I have no idea why the
results[i]
return
undefined
inside
then
function loop. Any help (or alternative ways to solve this) appreciated. Thanks!

Answer

I have no idea why the results[i] return undefined inside then function loop.

Because you don't have a loop in the .then() function. So i has the value it had at the end of the loop that created all the promises, which is the number of promises that were created. But the indexes of results go from 0 to i-1.

Promise.all(promises).then(function(results) {
  for (var i = 0; i < results.length; i++) {
    if (results[i] == d.source.name) {
      console.log("1");
      lelangmodal.push(lelang[i] + " - dimenangkan oleh " + d.source.name);
      console.log(lelangmodal);
    } else if (results[i] == d.target.name) {
      console.log("2");
      lelangmodal.push(lelang[i] + " - dimenangkan oleh " + d.target.name);
      console.log(lelangmodal);
    } else {
      console.log("3");
      lelangmodal.push(lelang[i]);
      console.log(lelangmodal);
    }
  }
  $('#modalLelang').text(lelangmodal);
  $('#myModal').modal('show');
});
Comments