gpt4 book ai didi

javascript - 同步 JavaScript 函数

转载 作者:行者123 更新时间:2023-12-02 17:56:42 28 4
gpt4 key购买 nike

如何使我的功能同步

$.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?

最佳答案

当所有对 getJSON 的调用完成后,您可以调用 setGraph(jsonGrpah),如下所示:

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

关于javascript - 同步 JavaScript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20923924/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com