katavie katavie - 5 months ago 33
JSON Question

How to force synchronous execution of getJSON?

For a school history project, I'm making a timeline webpage (live here). To avoid having to repeatedly type the details for each, I put them in a spreadsheet and exported it as JSON.

In the nav, I created links labelled with the year of the event using Javascript.

I want to then use slick.js, a jQuery plugin, to turn the nav into a carousel, as demonstrated an the /slick-test-static.html of the live website linked above.

My code:

$(document).ready(function(){
$.getJSON("data.js", function(result){
for (var i = 0; i < result.length; i++){
var string = JSON.stringify(result[i]);
var parsed = JSON.parse(string);

$('.slider').append("<li><a href=\"#" + parsed.number + "\">" + parsed.year + "</a></li>");
}
});

$('.slider').slick({
slidesToShow: 8,
slidesToScroll: 5,
autoplay: true,
autoplaySpeed: 3000
});
});


The links are created, but the slider isn't. I made a page where the links are created not using JSON, and it worked fine.

I think the problem is because the getJSON method is asynchronous, so the browser tries to create the slider before any items are even added to the slider. First, is this the problem? If so, what's the best way to fix it?

Answer

You can't make this synchronous. With ES6 you can "fake" waiting on asynchronous actions using async and await but what it's doing is essentially the same as what you need to do to make this work.

You need to stick your $('.slider').slick(... code inside of the $.getJSON callback. You should not initialize the slider until the async callback is made.

Comments