0

How can I make my function sync

$.getJSON(service_url + '?callback=?', params, function(response) {
    //console.log(response.result); 
    jsonGrpah = new Object();
    jsonGrpah.name = $("#label").val();
    jsonGrpah.children = new Array();
    for (var i = 0; i < response.result.album.length; i++)
    {
        jsonGrpah.children.push({"name": response.result.album[i]});
        jsonGrpah.children[i].children = new Array();
        var trackQuery = {"type": "/music/artist",
            "name": "The Police",
            "album": response.result.album[i],
            "track": []
        };
        var trackParams = {'key': API_KEY,
            'query': JSON.stringify(trackQuery)
        };
        $.getJSON(service_url + '?callback=?', trackParams, function(response) {
            for (var j = 0; j < response.result.track.length; j++)
            {
                jsonGrpah.children[i].children.push({"name": response.result.track[j]});
            }
        });
    }
    setGraph(jsonGrpah);
});

when I run it the setGraph(jsonGrpah); function run before the second json, there is a way to make a sync JavaScript?

Krish R
  • 22,583
  • 7
  • 50
  • 59
royb
  • 693
  • 3
  • 9
  • 20
  • don't do sync ajax request, it is just not the purpose of ajax. Anyway, jsonp doesn't support sync request – A. Wolff Jan 04 '14 at 17:04

1 Answers1

2

You can call setGraph(jsonGrpah) when all the calls to getJSON have completed like this:

$.getJSON(service_url + '?callback=?', params, function(response) {
    ...

    var calls = [];

    for (var i = 0; i < response.result.album.length; i++)
    {
        ...

        calls.push($.getJSON(service_url + '?callback=?', trackParams, function(response) {
            ...
        }));

        $.when.apply($, calls).then(function() {
            setGraph(jsonGrpah);
        });
    }
});
John S
  • 21,212
  • 8
  • 46
  • 56
  • see this answer: http://stackoverflow.com/questions/14989628/use-jquery-deferreds-for-variable-number-of-ajax-requests i could it solve the problem with deferreds – Frogmouth Jan 04 '14 at 17:23