0

I am having some issues with synchronous calls, and can't seem to understand exactly what's going wrong.

When debugging the code, it fills up the songTracks array perfectly, just until the return statement, where it is empty again.

Code sample:

function getAllSongIds(lijstId){
  var songTracks = [];
  $.ajax({
    url: "http://somehost.com/lists/"+lijstId+"/editions/",   
      dataType: "jsonp",
      async: false,
      success: function(json){

        for (i in json.editions) {
          $.ajax({
            url:"http://somehost.com/lists/"+lijstId+"/editions/"+json.editions[i].id,
            dataType:"jsonp",
            async: false,
            success: function(json2){
              for(j in json2.tracks){
                if(songTracks.indexOf(json2.tracks[j].id) === -1){
                  songTracks.push(json2.tracks[j].id);
                }
              }
            }
          })
        };
      }

    });
  alert(songTracks);
  return songTracks;
};

1 Answers1

7

JSONP is always asynchronous. The async: false setting is simply ignored. From the documentation:

[...] If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation.

Why?

JSONP has actually nothing to do with Ajax. jQuery is just providing a single function to deal with both. JSONP is nothing else but appending a <script> element to the document. The browser will load these scripts asynchronously.

See How do I return the response from an asynchronous call? for possible (asynchronous) solutions.

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143