I am struggling to get my head around async/promises using Javascript.
This issue is: I have an unknown number of pages to fetch. This only becomes apparent when there is no data returned when attempted.
In summary:
There is a defined base url (postedUrl)
The ‘page’ number parameter increments by 1 every time a fetch has been completed (and contains data)
Using axios (or what ever) to fetch the page and store the data in a global array – accessible later on
The issue I am having is, being able to successfully run the fetch an unknown amount of times (till there is no more data returned).
Note: The page number is not supposed to be used in the do/while loop. I could not get it to correctly alter isWorking to 0, and stop itself. So I used a temp solution so I could test out the code.
Can anyone advise the best way to do this?
const getHostname = (url) => {
return new URL(url).hostname;
}
let isWorking = 1;
let postedUrl = "https://example.com/"
let parsedUrl = getHostname(postedUrl)
let page_number = 110;
let total_products = 0;
let productList = [];
async function fetchData() {
axios.get(postedUrl,
{
params: {
page: page_number
}
})
.then((response) => {
console.log(response);
if (response.data.length == 0) {
isWorking = 0;
alert("is triggering");
}
})
.catch((err) => {
console.log(err);
});
console.log(isWorking);
page_number++;
}
async function startWork() {
do {
await fetchData();
console.log(isWorking);
} while (page_number < 115)
}
startWork();
2
Answers
Recursion could be the answer here. Just try
If the pages are independent of each other, you can get all of them at the same time using
Promise.allSettled()
, which returns aPromise
that fulfills when allPromise
s passed to it has settled:Try it: