1

i have an issue when i want to take the values and read it of arrayDevice, arrayidDevice, arrayDomCommande, arrayidCommande from outside of my function lectureCommand. Thanks you for helping me :)

  • This is what i get with console.log("test "+ arrayDevice[0]) : test undefined

  • This is what i get inside ajax for device[i].name : VM641:25 ajax Random-Integer-Generator01 VM641:25 ajax Random-Boolean-Device VM641:25 ajax Random-Integer-Device VM641:25 ajax Random-UnsignedInteger-Device VM641:25 ajax Random-Float-Device

And finally this is what i get with console.log(arrayDevice) : [] 0: "Random-Integer-Generator01" 1: "Random-Boolean-Device" 2: "Random-Integer-Device" 3: "Random-UnsignedInteger-Device" 4: "Random-Float-Device"

This is code :

$(document).ready(function() {
  // Declaration 
  arrayDevice = [];
  arrayidDevice = [];
  arrayDomCommande = [];
  arrayidCommande = [];
  arrayDescription = [];

  // Get des données lues dans core-data
  function getCommand() {
    var nameDevice = [];
    var idDevice = [];
    var nomCommande = [];
    var idCommande = [];
    $.ajax({
      url: '/core-command/api/v1/device',
      type: 'GET',
      success: function(device) {

        for (var i in device) {
          // Noms des périphériques 
          console.log("ajax " + device[i].name);
          nameDevice = device[i].name;

          // Noms des id du device
          //console.log(device[i].id);
          idDevice = device[i].id;

          // Nom des commandes du device 
          // console.log(device[i].commands[i]);
          nomCommande = device[i].commands[0].name;

          // id de la commande 
          //console.log(device[i].commands[0].id);
          idCommande = device[i].commands[0].id;
          lectureCommand(nameDevice, idDevice, nomCommande, idCommande);
        }
      }
    });
  }

  function lectureCommand(nameDevice, idDevice, nomCommande, idCommande) {
    arrayDevice.push(nameDevice);
    arrayidDevice.push(idDevice);
    arrayDomCommande.push(nomCommande);
    arrayidCommande.push(idCommande);
  }
  console.log("test " + arrayDevice[0]);
Barmar
  • 741,623
  • 53
  • 500
  • 612
Wsaitama
  • 75
  • 2
  • 11
  • Ajax is asynchronous and the array has an item only after the request is fulfilled, when `lectureCommand ` is invoked. The `console.log` was executed even before the request comes back so you would see it as undefined – Sushanth -- Nov 11 '19 at 20:33
  • So, what should i do solve my problem ? – Wsaitama Nov 11 '19 at 20:53

0 Answers0