Summary
I'd like to collate paginated output into an array using JavaScript's Fetch API recursively. Having started out with promises, I thought an async/await function would be more suitable.
Attempt
Here's my approach:
global.fetch = require("node-fetch");
async function fetchRequest(url) {
try {
// Fetch request and parse as JSON
const response = await fetch(url);
let data = await response.json();
// Extract the url of the response's "next" relational Link header
let next_page = /<([^>]+)>; rel="next"/g.exec(response.headers.get("link"))[1];
// If another page exists, merge it into the array
// Else return the complete array of paginated output
if (next_page) {
data = data.concat(fetchRequest(next_page));
} else {
console.log(data);
return data;
}
} catch (err) {
return console.error(err);
}
}
// Live demo endpoint to experiment with
fetchRequest("https://jsonplaceholder.cypress.io/posts?_page=9");
For this demo, it should result in 2 requests which yield a single array of 20 objects. Although the data is returned, I can't fathom how to collate it together into an array. Any guidance would be really appreciated. Thanks for your time.
Solution #1
Thanks to @ankit-gupta:
async function fetchRequest(url) {
try {
// Fetch request and parse as JSON
const response = await fetch(url);
let data = await response.json();
// Extract the url of the response's "next" relational Link header
let next_page;
if (/<([^>]+)>; rel="next"/g.test(response.headers.get("link"))) {
next_page = /<([^>]+)>; rel="next"/g.exec(response.headers.get("link"))[1];
}
// If another page exists, merge its output into the array recursively
if (next_page) {
data = data.concat(await fetchRequest(next_page));
}
return data;
} catch (err) {
return console.error(err);
}
}
fetchRequest("https://jsonplaceholder.cypress.io/posts?_page=9").then(data =>
console.log(data)
);
For each page, subsequent calls are made recursively and concatenated together into one array. Would it be possible to chain these calls in parallel, using Promises.all, similar to this answer?
On a side note, any ideas why StackOverflow Snippets fails on the second Fetch?