I have a callback function which hits a wordpress api multiple times and concatenates an array of posts of a specific category from the response. It works fine however when it gets to the last call it adds some duplicates to the array which i think is causing problems further down the line.
I've tried to remove these duplicates using a set but for some reason these duplicates are still being returned.
below i'm logging the length of the array.
At the time of writing there are:
40 unique posts of category blog
257 unique posts of category features
however for the features the array still contains 300 items
Does anyone have any idea why this might be happening ?
function getPostsOfType(category) {
return new Promise((resolve, reject) => {
const getData = (category, number = 0, page = 0) =>
fetch(`https://public-api.wordpress.com/rest/v1/sites/www.accessaa.co.uk/posts?category=${category}&number=${number}&page=${page}&order_by=date`)
.then(res => res.json())
const found = (category) => getData(category).then(json => json.found);
found(category)
.then((value) => {
return Math.ceil(value/100);
})
.then((callsToMake) => {
let tasks = [];
for (i = 0; i < callsToMake; i++) {
tasks.push(getData(category, 100, i)) //<--- Fill tasks array with promises that will eventually return a value
}
return Promise.all(tasks); //<-- Run these tasks in parallel and return an array of the resolved values of the N Promises.
})
.then((arrOfPosts) => {
let allPosts = [];
for(var elem of arrOfPosts)
allPosts = allPosts.concat(elem.posts);
console.log(Array.from(new Set(allPosts)).length);
}).catch((err) => {
console.log(err);
reject(err);
})
})
}
getPostsOfType('blog') //returns 40
getPostsOfType('features') //should return 257(ish) still returns 300