Javascript 如何使用ajax创建数组并在没有回调函数的情况下对其进行修改?
我试图使用回调来消除代码中的同步ajax调用,但我不知道这是如何工作的。我使用spotify API获取播放列表中的所有艺术家,然后根据这些信息执行任务。代码的基本逻辑是:Javascript 如何使用ajax创建数组并在没有回调函数的情况下对其进行修改?,javascript,jquery,ajax,recursion,spotify,Javascript,Jquery,Ajax,Recursion,Spotify,我试图使用回调来消除代码中的同步ajax调用,但我不知道这是如何工作的。我使用spotify API获取播放列表中的所有艺术家,然后根据这些信息执行任务。代码的基本逻辑是: 获取用户的播放列表选择 使用这些播放列表中的艺术家ID填充阵列 基于阵列进行更多ajax调用 使用步骤3中的数组执行另一项任务 问题是,如果我不将步骤2和3设置为同步,步骤4将出现在步骤2和步骤3之前。但我不能只调用步骤2末尾的步骤3和步骤3末尾的步骤4函数,因为它们都发生在while循环中。我想不出解决办法 调用函数 这个
artistArray = [];
while (artistUrls[i] != null) {
getArtists(artistArray, artistUrls[i]);
i++;
}
doSomethingWithArtistArray(artistArray);
doAnotherThingWithArray(artistsArray);
ajax功能
使用ajax调用获取艺术家信息并将其附加到数组中
getArtists(artistArray, url) {
(if (url == null) {
return;
}
$.ajax({
async: false,
url: url,
headers: {
'Authorization': 'Bearer ' + access_token
},
error: function() {
console.log("Something went wrong with " + url);
return;
},
success: function(tracks) {
getArtists_Append(artists, frequencyArray, tracks); //Uses a while loop to append all the artist information to artistArray
},
});
//My idea was to call doSomethingWithArtistArray here but that's not working because there might be more calls to make.
console.log("finished getting artists");
return;
}
}
获取艺术家=
getArtists_Append {
while loop that populates the array
}
问题是,当Ajax请求是异步的时,您将其视为同步的(您应该这样做以防止阻塞浏览器) 最好的办法是:
doSomethingWithArtistArray
Promise.all()
传递一个承诺数组,其中每个承诺包装一个Ajax请求。当您已经知道需要发出什么请求,并且不需要请求的响应来确定下一个要发出的请求时,这非常有用$。退房如果您喜欢承诺的想法并计划对Web API提出其他请求,我建议您使用包装器(无耻的自我提升)。有了这些,你可以简单地做到:
var api = new SpotifyWebApi();
var promises = [];
promises.add(api.getArtists(['id1', 'id2', 'id3', 'id4', 'id5']));
promises.add(api.getArtists(['id10', 'id11', 'id12', 'id13', 'id14']));
Promise.all(promises).then(function(data) {
// data contains the result of the promises (ajax requests)
// do something with it
});
您不能在getArtists
ajax函数的success
函数中调用doSomethingWithArtistaray
?然后在doSomethingWithStarray
ajax函数的success
函数中调用doNothingWithArray
?您可能需要的是使用promise
,或者用jQueery的话说,$。延迟的应该可以工作。。使用async:false
。。。但这不是一个好的解决方案,使用。。。尤其是在循环中。。。。这样做有什么特别的原因吗?函数中有一些语法错误。谢谢你的快速回复(尽管我的回复很晚)!我用承诺让它工作,我对结果很满意。我唯一的问题是,对艺术家的相关艺术家的一些回应是没有定义的。我会自己解决的。检查那些艺术家在Spotify应用程序的Spotify页面中是否有相关艺术家。如果有,则应退还。您还可以使用Web API控制台轻松地检查请求