簡體   English   中英

使用Promise獲取Ajax數據

[英]Using promises to get ajax data

我一直在嘗試讓代碼的其余部分等待ajax調用運行,然后再執行,因為我首先需要數組中的信息。 我嘗試了多種方法,但是我無法弄清楚為什么它們不能。 在這種情況下,似乎最好使用諾言。 當前,ajax仍在.done和最終console.log(3)之后運行。

請參見下面的代碼:

$(document).ready(function(){
    var selectedChannels = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];
    var numberOfChannels = selectedChannels.length;
    var onlineChannels = [];
    var offlineChannels = [];

function getChannels(){

 for (var count = 0 ; count < numberOfChannels; count++) {

    $.ajax({
    url: "https://wind-bow.hyperdev.space/twitch-api/streams/"+ selectedChannels[count],
    type: "get",
    dataType: "jsonp",
    callback: "?",
      data: {
        }, 
        success: function(data) {
            if (data.stream) {
              var logo = data.stream.channel.logo
              var twitchName = data.stream.channel.display_name
              var details = data.stream.channel.status
              var link = data.stream.channel.url
              onlineChannels.push(twitchName);
              console.log(onlineChannels);
              console.log(1);

              $(".display-area").append("<div class=\"result-box online\"><img src="+ logo +" alt=\"twitchName\" class=\"profile-img\"></img><div class=\"title\">"+ twitchName +"</div><div class=\"description\">"+ details +"</div>");

            } 
        },
    }).done(function(){

    });
 }

 }

/* should run after ajax and onlineChannels array has been populated */
 function completeAjax() {
  var promised = getChannels();
  var promisedComplete = $.when(promised);
  promisedComplete.done(function(){
    console.log(onlineChannels);
    console.log(2);
  });
}

completeAjax();

console.log(3)
});

您可以映射ajax調用並返回promise,然后使用$.when.apply檢查所有ajax調用是否已完成

$(document).ready(function() {
    var selectedChannels = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];
    var onlineChannels   = [];
    var offlineChannels  = [];

    function getChannels() {
        return $.map(selectedChannels, function(channel, index) {
            return $.ajax({
                url      : "https://wind-bow.hyperdev.space/twitch-api/streams/" + channel,
                type     : "GET",
                dataType : "jsonp",
                callback : "?",
                data     : {}
            }).done(function(data) {
                if (data.stream) {
                    var logo       = data.stream.channel.logo;
                    var twitchName = data.stream.channel.display_name;
                    var details    = data.stream.channel.status;
                    var link       = data.stream.channel.url;

                    onlineChannels.push(twitchName);

                    $(".display-area").append("<div class=\"result-box online\"><img src=" + logo + " alt=\"twitchName\" class=\"profile-img\"></img><div class=\"title\">" + twitchName + "</div><div class=\"description\">" + details + "</div>");
                }
            });
        });
    }

    $.when.apply($, getChannels()).done(function() {
        // all done, onlineChannels populated
    });

});

您可以使用計數器倒數為零,以查看仍有多少Ajax調用需要完成:

for (var count = 0 ; count < numberOfChannels; count++) {
    $.ajax({
        // ...
        success: function(data) {
            count--; // <!--------- decrease count
            // ...
        },
    }).done(function(){
        if (!count) { // <!--------- see if this was the last one finishing.
            // All Ajax done.
            // ...following tasks are initiated here.
            //
        }
    });
}

要了解它是如何工作的,重要的是要認識到,在循環完成之前,未success調用successdone回調,並且count已達到最大值。 從那時起, count只會減少。

暫無
暫無

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

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