JavaScript Wait until all async calls finish

前端 未结 3 1499
礼貌的吻别
礼貌的吻别 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:15

    With promises, you should not use a callback parameter. Call the resolve/reject functions from the promise instead.

    Instead of passing a callback to the call, chain the things you want to do with the result of the promise in a .then handler.

    function httpGet(theUrl) {
        return new Promise(function(resolve, reject) {
            var xmlRequest = new XMLHttpRequest();
            xmlRequest.onreadystatechange = function() {
                if (xmlRequest.readyState == 4) {
                    if (xmlRequest.status == 200) 
                        resolve(xmlRequest.responseText);
        //              ^^^^^^^
                    else
                        reject(new Error(xmlRequest.statusText)); // or something
                }
            }
            xmlRequest.open("GET", theUrl, true);
            xmlRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            xmlRequest.setRequestHeader("Accept", "application/json");
            xmlRequest.send(null);
        });
    }
    $(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 promises = urls.map(function(url) {
    //                      ^^^ simpler than forEach+push
            var promise = httpGet(url); // <-- no callback
            return promise.then(JSON.parse);
        });
    
        Promise.all(promises).then(function(data) {
    //                                      ^^^^
            console.log(data);
        });
    })
    

提交回复
热议问题