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

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

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);
});
```

![](https://2726517656-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M1E4Gk2ppVKb4olmnun%2Fuploads%2FyI96bNxx9buppmopcxYE%2FScreenshot_4.png?alt=media\&token=c9b48b1e-9d35-4a04-95eb-6669c96c1534)

![](https://2726517656-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M1E4Gk2ppVKb4olmnun%2Fuploads%2FkQDLXu436FB3CRgY8ctT%2FScreenshot_5.png?alt=media\&token=608079fc-c346-4efa-b047-3a3931c47aeb)

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);
  }
);
```

![](https://2726517656-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M1E4Gk2ppVKb4olmnun%2Fuploads%2F738al4XZW3ZlwJ8TVAn7%2FScreenshot_3.png?alt=media\&token=3b05fe0c-04db-4d13-a7f8-d35fa6bf13ff)
