简体   繁体   中英

Do something when variable is not undefined

I have a function (eg getContent(); ) in a script written in JavaScript that gets the XML content from a page, converts it to JSON and stores it in a variable (eg var resultsJSON; ). This process takes 0.07 seconds to do, but it is still not fast enough for the rest of the script. The script then is supposed to use a portion of the JSON. When I test it, the console says that the variable resultsJSON is undefined. I put a console.log in the function to see when it actually gets the XML and stores it in the variable. It looks like the code is sent to get the content, and then the script continues running the next line of code after that before the content is added to the variable.

I would think that the issue has to do with the code being synchronous versus asynchronous. I have tried to learn about that, but I am having some trouble understanding it, partly due to me being new at JavaScript. How would I make the script wait for the variable to not be undefined before continuing with the rest of the script? Here is an example of what my script looks like:

var resultsJSON;
getContent();//gets XML from page, converts XML to JSON, makes resultsJSON = JSON
var item=resultsJSON.Item[0];
console.log(item);

The last two lines need to wait before being executed until resultsJSON has a value. How would I do this?

Just to let you know, I am able to use JQuery, but would prefer not to unless I absolutely have to.

Here is what the getContent function looks like:

function getContent() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            resultsJSON = xml2json.fromStr(this.responseText);
            console.log(resultsJSON);
        }
    };
    xhttp.open("GET", 'getResults.php?'+queryURL, true);
    xhttp.send();
}

I removed the variables defined inside of the function since they are irrelevant to the issue. The queryURL variable is one of these variables. This function uses a script called xml2json from here ; the xml2json is defined in that script.

This doesn't really appear to be a synchronous vs. asynchronous problem, but rather a basic understand of what JS does problem.

var resultsJSON;
getContent();//gets XML from page, converts XML to JSON, makes resultsJSON = JSON
var item=resultsJSON.Item[0];
console.log(item);

In your code above, the function getContent(); will execute immediately and then the JS engine will go to the next line where you're trying to read the response. However, the call to get the xml page likely hasn't completed yet. You should make getContent(); return your value rather than set a variable that is already declared. Inside of getContent(); only return the value after the call has completed.

var resultsJSON = getContent();//gets XML from page, converts XML to JSON, makes resultsJSON = JSON
var item = resultsJSON.Item[0];
console.log(item);

Here's a quick demo of a callback and how you may be able to apply it to your problem. Essentially, you send your getContent() function the name of another function -- and then once getContent() resolves, you can then trigger the next function to continue on with your code:

 var resultsJSON = {}; getContent( printResult ); // ^Pass in the function name that you want // to get executed after getContent() resovles function getContent( callback ){ // ^ 'callback' is just a variable // name at this point. This variable refers to the function // passed in, to be called back later // a timeout to mimic something that takes some time, in this // case 3 seconds setTimeout( function(){ resultsJSON.Item = []; resultsJSON.Item[0] = 'apple'; callback(); // ^invoke the callback function, in this case, it's calling // printResult(); }, 3000 ); } function printResult(){ console.log(resultsJSON); } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM