1

I'm trying to use global arrays to store some data to be used at a later course.

However when I run through the chrome debugger console the push function doesn't add them to the array associated either, nor do I get any errors.

I've looked at many other examples and cannot see where I'm going wrong.

Could someone show me where I'm going wrong?

JavaScript:

var hv = ['1', '2', '3', '4'];

$(document).ready(function () {
    for (var i = 0; i < hv.length; i++) {
        GetVmsOnHyper(hv[i]);
    }
});

function GetVmsOnHyper(id) {
    $.ajax({
        type: "GET",
        url: "/api/function/" + id,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: virtualmachineinfo
    })
}

var avrg_mem = [];
var avrg_cpu = [];
var avrg_lng = [];

function virtualmachineinfo(vmData) {

    var vmcount = vmData.length;
    avrg_lng.push(vmcount);

    var mem_size = "medium";
    var cpu_size = "medium";
    for (var i = 0; i < vmData.length; i++) {
        var vm_mem = vmData[i].memory;

        if (vm_mem > 6143) {
            mem_size = "large";
        }
        else if (vm_mem < 2047) {
            mem_size = "small";
        }
        avrg_mem.push(mem_size);

        var vm_cpu = vmData[i].cpus;

        if (vm_cpu > 4) {
            cpu_size = "large";
        }
        else if (vm_cpu < 2) {
            cpu_size = "medium";
        }
        avrg_cpu.push(cpu_size);
    }

Solution

Not a solution as such but building a function to check the contents of the array rather than just going on what the Chrome debug console told me shows that the code was working.

Adding the below at the end to check:

function checkArrays() {
    for (i = 0; i < avrg_mem.length; i++) {
        var whatis = avrg_mem[i];
    }
PurpleSmurph
  • 2,055
  • 3
  • 32
  • 52
  • 1
    try removing the "var" before the name of your GLOBAL variable. Just "avrg_mem = [];" – Julo0sS Jul 08 '15 at 07:51
  • 1
    It isn't declared anywhere else though, does it not need to be? – PurpleSmurph Jul 08 '15 at 07:53
  • Duplicate of [How to return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – JJJ Jul 08 '15 at 07:58
  • Apologies all, the amended question showing full code is now there. – PurpleSmurph Jul 08 '15 at 07:58
  • No Juhana, the response is fine. The issue is the arrays are not being accessed when pushed and I can't figure out why. – PurpleSmurph Jul 08 '15 at 07:59
  • Yes, the response is fine, but you're checking the arrays before the query returns. Read the duplicate. – JJJ Jul 08 '15 at 08:00
  • I have read the other question, however I am getting information back and iterates through the loop, displaying all of the data for each object but it is not pushing to the arrays, the query has returned surely, otherwise I would be pushing an undefined variable, which it isn't according to the console - if the ajax query is the issue, where/when should I be pushing to the array in that function? – PurpleSmurph Jul 08 '15 at 08:10
  • 1
    Your code still doesn't show where you're checking those arrays so it's not possible to say anything for certain. – JJJ Jul 08 '15 at 08:12
  • 2
    You're probably pushing the data to the arrays just fine. But whatever other code in your app tries to *use* those arrays is not seeing it, because that code is running *before* the code in `virtualmachineinfo()` runs. You shouldn't be thinking in terms of global arrays here at all. Instead, your other code should be in a function that `virtualmachineinfo()` should call. Then you don't need globals at all and everything will work. – Michael Geary Jul 08 '15 at 08:12
  • Juhana - I was going through the Chrome console and when the arrays are in the function, then I can see the variables being pushed to the arrays. Would it be best to create another function that reads from those arrays, is the chome console not accurate for how I've been using it? Michael - Thanks for the suggestion, I need to initialise them before the `virtualmachineinfor()` so that I can push into them? The reason they are globals is so that other functions will be able to use them. – PurpleSmurph Jul 08 '15 at 08:17
  • Thank you Juhana and Michael - it was me being a muppet, code worked, just didn't give it a chance, `function checkArrays() { for (i = 0; i < avrg_mem.length; i++) { var whatis = avrg_mem[i]; }` as a checked function shows that they were being populated. – PurpleSmurph Jul 08 '15 at 08:36
  • why don't you use some kind of callback functions on your ajax call to be sure it is executed before calling virtualmachineinfo??? oO (to me, global vars are not a problem) – Julo0sS Jul 08 '15 at 08:37

1 Answers1

1

Your arrays are updated correcty. You can see it in the example (open console before), I replace ajax function by similar logic function: https://jsfiddle.net/gzfLL0uv/

var hv = ['1', '2', '3', '4'];

$(document).ready(function () {
    for (var i = 0; i < hv.length; i++) {
        GetVmsOnHyper(hv[i]);
    }
});

function GetVmsOnHyper(id) {

    setTimeout(function() {
        virtualmachineinfo([{memory: id * 100, cpus: 111},
                            {memory: id * 100, cpus: 222},
                            {memory: id * 100, cpus: 333}]);
    }, 1000);
}

var avrg_mem = [];
var avrg_cpu = [];
var avrg_lng = [];

function virtualmachineinfo(vmData) {

    var vmcount = vmData.length;
    avrg_lng.push(vmcount);

    var mem_size = "medium";
    var cpu_size = "medium";
    for (var i = 0; i < vmData.length; i++) {

        //console.log(i);
        var vm_mem = vmData[i].memory;

        if (vm_mem > 6143) {
            mem_size = "large";
        }
        else if (vm_mem < 2047) {
            mem_size = "small";
        }
        avrg_mem.push(mem_size);

        var vm_cpu = vmData[i].cpus;

        if (vm_cpu > 4) {
            cpu_size = "large";
        }
        else if (vm_cpu < 2) {
            cpu_size = "medium";


   }
        avrg_cpu.push(cpu_size);
    }

    console.log(avrg_lng);
}

You can be confused that arrays are empty if you try to check it after virtualmachineinfo function in code. You need to do it just in virtualmachineinfo function because your code works like that:

  1. Init of functions and variables firstly
  2. Register to observe the DOM ready event
  3. Handle this event and iterate hv variable, where call GetVmsOnHyper and register new event on ajax request will be resolved
  4. Call virtualmachineinfo function asynchronously four times.

So, after last point your arrays will be filled by all values.

You should use Promises or Defer in Jquery lib to catch the moment when all ajax requests will be resolved.

iamarsey
  • 211
  • 2
  • 12