Javascript - Wait for function to return

Posted by LoadData on Stack Overflow See other posts from Stack Overflow or by LoadData
Published on 2014-06-08T21:22:35Z Indexed on 2014/06/08 21:24 UTC
Read the original article Hit count: 144

Filed under:
|
|

So, I am working on a project which requires me to call upon a function to get data from an external source.

The issue I am having, I call upon the function - However the code after the function call is continuing before the function has returned a value.

Here is the function -

function getData()
{
    var myVar;
    var xmlLoc = $.get("http://ec.urbentom.co.uk/StudentAppData.xml", function(data) {
        $xml = $(data);
        myVar = $xml;
        console.log(myVar);
        console.log(String($xml));
        localStorage.setItem("Data", $xml);
        console.log(String(localStorage.getItem("Data")));
        return myVar;
    });
    return myVar;
    console.log("Does this continue");
}

And here is where it is called upon -

$(document).on("pageshow","#Information",function() {
    $xml = $(getData()); //Here is the function call
    console.log($xml); //However, it will instantly go to this line before 'getData' has returned a value.
    $xml.find('AllData').each(function() {
        $(this).find('item').each(function() {
            if ($(this).find('Category').text()=="Facilities") {
                console.log($(this).find('Title').text());
                //Do stuff here
            } else if ($(this).find('Category').text()=="Contacts" || $(this).find('Category').text()=="Information") {
                console.log($(this).find('Title').text());
                //Do stuff here too
            }
        });
        $('#informationList').html(output).listview().listview("refresh");
        console.log("Finished");
    });
});

Right now, I'm unsure of why it is not working. My guess is that it is because I am calling a function within a function.

Does anyone have any ideas on how this issue can be fixed?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery