Использование ax ios .get внутри цикла for - PullRequest
0 голосов
/ 29 марта 2020

У меня есть массив ссылок для получения данных. Как мне ждать, пока он завершит процесс, и получить данные из топора ios.

function site1(url,arr){
        for(i=0;i<arr.length;i++){
              axios.get(url)
                  .then(response=>{
                    const $=cheerio.load(response.data);
                    //get desired data from site
                    //modify the array
                  }
    }    
 }

Теперь, как мне заставьте мой код дождаться завершения этого процесса и вытащите из него измененный массив.

Ответы [ 3 ]

1 голос
/ 29 марта 2020

Вы можете попробовать сопоставить массив с массивом обещаний и ожидать их с Promise.all ()

const promises = arr.map(item => axios.get(item.url));

const result = await Promise.all(promises);
console.log(result); // [...]
/* or */

Promise.all(promises).then(result => {
  console.log(result); // [...]
});
1 голос
/ 29 марта 2020

Создайте обещание и pu sh в массиве, затем разрешите все, чтобы получить значения.

function site1(url, arr) {
  let promises = [];
  for (i = 0; i < arr.length; i++) {
    promises.push(
      axios.get(url).then(response => {
        const $ = cheerio.load(response.data);
        return $;
      })
    );
  }
  return Promise.all(promises);
}
site1("https://google.com", [1, 2, 3, 4]).then(results => {
  console.log(results);
});

// Простой:

const urls = ["url1", "url2"];
const promises = urls.map(url => axios.get(url));
Promise.all(promises).then(results => {
  console.log(results);
});
0 голосов
/ 29 марта 2020

Вы можете использовать ax ios .all .it ожидает массив обещаний

Тест ниже

//three urls
let promises=[],urls=["https://api.covid19api.com/country/NetherLands/status/deaths",
"https://api.covid19api.com/country/NetherLands/status/recovered",
"https://api.covid19api.com/country/NetherLands/status/active"];
urls.forEach( (url) => promises.push(axios.get(url))) 
axios.all(promises).then(axios.spread(function (res) {console.log(res);}));
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
...