😁How to recursively fetch data from paginated API then combine into one array (ok)

https://stackoverflow.com/questions/72420288/how-to-recursively-fetch-data-from-paginated-api-then-combine-into-one-array

D:\working\smarthr\code.js (lấy dữ liệu phần phân trang)

var settings = {
  "url": "https://55527790b6cf51206c3580fb.daruma.space/api/v1/crews/?page=1&access_token=jYM4cw3oWKXUjtbXboFkhB9vZgbshdEx",
  "method": "GET",
  "timeout": 0,
  "headers": {
    "Content-Type": "application/json"
  },
};
$.ajax(settings).done(function(response) {
  console.log(response);
});

D:\working\smarthr\test.html

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Document</title>
	<!-- Latest compiled and minified CSS & JS -->
	<script src="http://code.jquery.com/jquery.js"></script>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.27.2/axios.min.js"></script>
	<script type="text/javascript" src="code.js"></script>
</head>
<body>
	
</body>
</html>

D:\working\smarthr\code.js

const bigData = [];
async function fetchAllPaginateData(pageKey = 1) {
  try {
    const fetchURL = `https://55527790b6cf51206c3580fb.daruma.space/api/v1/crews/?page=${pageKey}&access_token=jYM4cw3oWKXUjtbXboFkhB9vZgbshdEx`;
    const response = await axios.get(fetchURL);
    if (response.data.length > 0) {
      const { data } = response;
      const totalPages = 3000;
      bigData.push(data);
      if (pageKey < totalPages) {
        pageKey++;
        await new Promise((resolve) => setTimeout(resolve, 200));
        return await fetchAllPaginateData(pageKey);
      }
      return console.info('Data complete.');
    }
  } catch (err) {
    console.error(err);
  }
}
fetchAllPaginateData().then(
  () => {
    var bigDatas = [];
    bigData.forEach(function(element, index) {
      element.forEach(function(element2, index2) {
        bigDatas.push(element2);
      });
    });
    console.log(bigDatas);
  }
);

Last updated

Navigation

Lionel

@Copyright 2023