I am looking to iterate through an array of users (with only the id property set), call an endpoint every two seconds with each id, and store the associated user's name from the response into an updated array.
e.g. update [{ id: 1 }]
to [{ id: 1, name: "Leanne Graham" }]
Here is my code:
const axios = require('axios');
const users = [{ id: 1 }, { id: 2 }, { id: 3 }];
function addNameToUser(user) {
return new Promise((resolve) => {
axios.get(`https://jsonplaceholder.typicode.com/users/${user.id}`)
.then(response => {
user.name = response.data.name
resolve(user);
});
})
}
const requests = users.map((user, index) => {
setTimeout(() => {
return addNameToUser(user);
}, index * 2000);
});
Promise.all(requests).then((updatedArr) => {
console.log(updatedArr);
});
Everything works great without the setTimeout
, but it's important that I only send a request every two seconds. So for three users, I would like to see the result from my Promise.all
log after six seconds or so.
Worth noting: This is not the actual problem I am working on, but the easiest example I could come up with to help highlight the issue.