JavaScript Wait until all async calls finish

前端 未结 3 1466
礼貌的吻别
礼貌的吻别 2021-01-27 04:46

I need some help with handling async calls in JavaScript. I have a for loop, each loop calls an async HttpRequest, and adds its response to an array. I want the program to wait

3条回答
  •  星月不相逢
    2021-01-27 05:19

    Since you are using jQuery you can use the Deferred Object to chain promises.

    Collect all the promises and use $.when with spread operator to wait for all promises to resolve. You can use then to run a function after all ajax requests are resolved.

    ES5 Example

    $(document).ready(function () {
    
        var channels = ["freecodecamp", "storbeck", "terakilobyte", "habathcx", "RobotCaleb", "thomasballinger", "noobs2ninjas", "beohoff"];
        var urls = channels.map(function (x) {
            return "https://api.twitch.tv/kraken/channels/" + x;
        });
        var data = [];
        var promises = urls.map(function (url) {
            return $.get(url).then(function (response) {
                data.push(response);
            });
        });
    
        $.when.apply($, promises).then(function () {
            console.log('done', data);
        });
    });

    ES6 Example

    $(document).ready(function() {    
        var channels = ["freecodecamp", "storbeck", "terakilobyte", "habathcx","RobotCaleb","thomasballinger","noobs2ninjas","beohoff"];
        var urls = channels.map((x) => "https://api.twitch.tv/kraken/channels/" + x);
        var data = [];
        var promises = urls.map((url) => $.get(url).then((response) => {
            data.push(response);
        }));
    
        $.when(...promises).then(function() {
            console.log('done', data);
        });
    });

提交回复
热议问题