I am looping over an array and calling an endpoint to fetch data per item. I want to call every 2 items together, then wait for 10 seconds and call the next two items and so on until the list is complete. I tried a solution but its not working. Please help me on what I am doing wrong.
Here is the code.
const data = [{
name: '1',
id: 1,
}, {
name: '2',
id: 2,
}, {
name: '3',
id: 3,
}, {
name: '4',
id: 4,
}, {
name: '5',
id: 5,
}, {
name: '6',
id: 6,
}]
const result = data.reduce(async(a, c, i) => {
let counter = 0;
if (counter > 2) {
setTimeout(() => {
counter = 0;
}, 10000)
}
const res = await a;
res.push({
name: c.name,
id: c.id,
title: (await (await fetch(`https://jsonplaceholder.typicode.com/posts/${c.id}`)).json()).title
})
await counter++;
return res
}, Promise.resolve([]))
result.then(a => console.log(a))