簡體   English   中英

如何使用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獲取多位藝術家的特定情況下,請使用端點來獲取多位藝術家 這將減少您需要向Spotify的Web API發出的請求數量。

  2. 如果使用回調函數,則將發出Ajax請求。 然后,在其回調中,您將檢查是否需要使用下一個塊再次發出Ajax請求。 如果您因為完成而無需發出任何其他請求,請調用下一個函數,在本例中為doSomethingWithArtistArray

  3. 如果您正在使用Promises,則使用Promise.all()傳遞一個Promise.all()數組,其中每個Promise.all()都會包裝一個Ajax請求。 當您已經知道需要發出什么請求並且不需要來自請求的響應來確定下一個要發出的請求時,此功能很有用。

請查看Spotify開發人員網站上的“ 代碼示例”部分 ,以查看使用Web API的一些開源網站。

例如,當獲取播放列表音軌時,您可以看到如何在“ 音樂排序”中應用第二種選擇。 如果有更多的軌道要提取,該函數將向下一個塊發出請求,否則不會。

對於第三種選擇,由於使用的是jQuery,因此可以使用$.when來使用promises。 看看這個例子 如果您喜歡promise的想法並計划對Web API提出其他請求,我建議您使用諸如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
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM