How to use multiple XMLHttpRequest?

后端 未结 3 921
青春惊慌失措
青春惊慌失措 2021-02-02 01:08

I need to get 8 JSON from 8 different URL. I stored the query string that I have to change in an Array and I loop through it with a for loop. Here is my code:

va         


        
3条回答
  •  半阙折子戏
    2021-02-02 01:19

    You may also prefer to use the Fetch API in the place of XMLHttpRequest. Then all you have to do is to utilize a few Promise.all() functions.

    var index = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"],
        url   = "https://wind-bow.glitch.me/twitch-api/channels/",
        proms = index.map(d => fetch(url+d));
    
    Promise.all(proms)
           .then(ps => Promise.all(ps.map(p => p.json()))) // p.json() also returns a promise
           .then(js => js.forEach((j,i) => (console.log(`RESPONSE FOR: ${index[i]}:`), console.log(j))));
    .as-console-wrapper {
    max-height: 100% !important;
    }

提交回复
热议问题