同步javascript函数

时间:2014-01-04 17:02:04

标签: javascript jquery html

如何使我的功能同步

$.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);
});

当我运行它时,setGraph(jsonGrpah);函数在第二个json之前运行, 有一种方法可以实现同步JavaScript吗?

1 个答案:

答案 0 :(得分:2)

setGraph(jsonGrpah)的所有来电完成后,您可以致电getJSON

$.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);
        });
    }
});