Smith
Smith

Reputation: 3

How do I make this function occur after two $.getJSON functions?

Originally, I had it with just $(document).ready(update()); but that didn't work since the first $.getJSON was too slow. When I added the setTimeout, the first $.getJSON loaded but the second one didn't. Now, I understand WHY this is happening (because JSON is asynchronous), but I don't understand how I am supposed to fix it. I've been looking at .then, but every time I use it, it seems I either use it incorrectly or it doesn't change the situation.

// Original Code

$.getJSON("workshops.json", function(data){
    workshopData = data;
});

$.getJSON("summers.json", function(data){
    summerData = data;
});

$(document).ready(function(){
    setTimeout(update(), 0);
});
// Attempt at .then
function gatherData(){
    $.getJSON("workshops.json", function(data){
        workshopData = data;
    });

    $.getJSON("summers.json", function(data){
        summerData = data;
    });
};

gatherData().then(function(e){
    update();
    console.log("test");
});

Upvotes: 0

Views: 42

Answers (2)

Nick Parsons
Nick Parsons

Reputation: 50684

You can use jQuery's $.when() method here. The $.when() method accepts a list of deferred parameters such as the jqXHR request returned by your $.getJSON method (you can think of jqXHR as an object which wraps the Promise interface). The $.when() will then run each deffered action concurrently and execute the .done() callback with resolved values as its arguments.

See example below:

function gatherData() {
  const jqxhr1 = $.getJSON("workshops.json");
  const jqxhr2 = $.getJSON("summers.json");
  return $.when(jqxhr1, jqxhr2);
}

gatherData().done(function(workshopData, summerData) {
  console.log("workshop data: ", workshopData);
  console.log("summer data: ", summerData);
  update(); // call update which can now access workshopData and summerData (if passed through)
});

Upvotes: 0

x00
x00

Reputation: 13823

If your are not yet ready for Promises and async/await. You can stick with "callback hell" for now:

$.getJSON("workshops.json", function(data){
    workshopData = data;
    $.getJSON("summers.json", function(data){
        summerData = data;
        update();
        console.log("test");
    });
});

When one request compiles it will call nested callback with the next request. And when it completes the second callback will call update

Upvotes: 1

Related Questions