如何用ajax创建一个数组并在没有回调函数的情况下修改它?

How to create an array with ajax and modify it without callback function?

我正在尝试使用回调来摆脱代码中的同步 ajax 调用,但我不知道它是如何工作的。我正在使用 spotify API 获取播放列表中的所有艺术家,然后根据该信息执行任务。代码的基本逻辑是:

  1. 获取用户的播放列表选择
  2. 用这些播放列表中的艺术家 ID 填充一个数组
  3. 根据数组进行更多 ajax 次调用。
  4. 使用第 3 步中的数组执行另一项任务。

问题是,如果我不将第 2 步和第 3 步设置为同步,第 4 步将先于第 2 步和第 3 步。但是我不能只在第 2 步结束时调用第 3 步,在第 3 步函数结束时调用第 4 步,因为两者都发生在 while 循环中。无法找到解决方案。

调用函数

此 while 循环遍历用户在多选框中的所有选择,并调用 ajax 函数追加数据。

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 请求视为同步请求,而实际上它们是异步的(您应该这样做以防止阻塞浏览器)。

最好的方法是:

  1. 在从 Spotify 获取多个艺术家的特定情况下,使用 getting several artists 的端点。这将减少您需要向 Spotify 的 Web API.

  2. 发出的请求数量
  3. 如果使用回调函数,您将发出 Ajax 请求。然后在其回调中,您将检查是否需要对下一个块发出另一个 Ajax 请求。如果您因为已完成而不需要发出任何其他请求,则调用您的下一个函数,在本例中为 doSomethingWithArtistArray.

  4. 如果您使用 Promises,则使用 Promise.all() 传递一个 promises 数组,其中每个 promise 包装一个 Ajax 请求。当您已经知道需要发出哪些请求,并且不需要请求的响应来确定要发出的下一个请求时,这很有用。

查看 Spotify 开发人员站点上的 Code Examples section,了解一些使用 Web 的开源站点 API。

例如,您可以在 Sort Your Music when getting playlists tracks 中看到如何应用第二个备选方案。如果有更多曲目要获取,该函数将请求下一个块,否则不会。

对于第三种选择,因为您使用的是 jQuery,所以您可以使用 $.when 来使用 promises。查看 this example. If you like the idea of promises and plan to make other requests to the Web API, I would recommend you using a wrapper like Spotify Web API JS(无耻的自我推销)。这样你就可以简单地做:

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