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?

1
  • don't do sync ajax request, it is just not the purpose of ajax. Anyway, jsonp doesn't support sync request Commented Jan 4, 2014 at 17:04

1 Answer 1

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);
        });
    }
});
Sign up to request clarification or add additional context in comments.

1 Comment

see this answer: stackoverflow.com/questions/14989628/… i could it solve the problem with deferreds

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.