mike-source
mike-source

Reputation: 1015

How to make JS function wait for JSON data to load?

This works:

function getDataJSON() {
    var queryString = "https://www.examplesite.com/someJSON.json";

    $.getJSON(queryString, function(data) {
        doStuffWithData(data)
    });
 }

 function doStuffWithData(JSON) {
     // some code that refers to JSON
 }

 getDataJSON();

But this complains that a variable (JSON) is undefined somewhere in doStuffWithData():

function getDataJSON(callback) {
    // Gets share data and runs callback when received
    var queryString = "https://www.examplesite.com/someJSON.json";

    $.getJSON(queryString, function(data) {
        if(typeof callback === "function") {
            callback(data);
        }
    });
 }

 function doStuffWithData(JSON) {
     // some code that refers to JSON
 }

getDataJSON(doStuffWithData());

What am I likely to be doing wrong? The $.getJSON() call takes a second or two so I do need to wait for that and do stuff after it. I think the issue is with the code execution order, but it could be that I've misunderstood how to properly pass the data to the callback function.

It would be better if I could just load the data into a variable all my other functions can access.

Upvotes: 0

Views: 2931

Answers (2)

rady
rady

Reputation: 428

You need to leave out the parenthesis in this call getDataJSON(doStuffWithData()); should be getDataJSON(doStuffWithData). The reason is that doStuffWithData is the function and doStuffWithData() is the retrun value from the function.

Upvotes: 1

Kevin F
Kevin F

Reputation: 2885

This:

getDataJSON(doStuffWithData());

should be this:

getDataJSON(doStuffWithData);

Otherwise it invoked that function immediately and attempts to pass the result of the function into getDataJSON

Upvotes: 7

Related Questions