0

I just started to practice code in asynchronous programming. And I'm little bit confused, why I could not get the application working correctly.

I'm trying to load json data in a var jsonItems. Load the sound, and play.

function getJItems(jsonItems, callback){

$.getJSON( "data.json", function( data ) {
    jsonItems.push(data);

});

    callback(jsonItems);    
}

var sI = [];

function loadSoundJson(jsonItems){

    for (it =0 ; it < jsonItems[0].length ; it++){
        sI[it] = new buzz.sound( "data/"+jsonItems[0][it].filesound, { formats: [ "ogg", "mp3"] });
    }

};

This is how I try to call.

$( document ).ready(function() {


    getJItems(jsonItems,loadSoundJson);

});

The error that I get is: jsonItems[0] is undefined

If I write, works fine.

$( document ).ready(function() {


    getJItems(jsonItems);
        window.alert("forced pause");
        loadSoundJson(jsonItems);

});

So, I just want to be sure, that whole content (images, sound, data) will be loaded and ready before the application starts.

Maybe what I want is, know how to implement the correct way to making a good loading page. thanks in advance.

cleliodpaula
  • 819
  • 2
  • 11
  • 27
  • It's async, you're trying to use the data before it's available, and this is a duplicate. – adeneo Mar 10 '14 at 15:07
  • possible duplicate of [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – adeneo Mar 10 '14 at 15:07

1 Answers1

0

Try this:

function getJItems(jsonItems, callback){

   $.getJSON( "data.json", function( data ) {
      jsonItems.push(data);
      callback(jsonItems); 
   });


}

You were not calling the callback at the right moment. getJSON is async hence when the data are available they will get pushed into jsonItems. At first callback(jsonItems); was being executed before any data was available.

What you were doing at the first place was execute getJItems() do an ajax call (without waiting for reply) call the callback

0x_Anakin
  • 3,229
  • 5
  • 47
  • 86