I am trying to retrieve an array list of object IDs from an API using axios. Once I have the object ID list, I want to fetch the details of each object using promises.
This is what I have in mind:
var objectDetail = [];
axios.get('apiendpoint/')
.then((response) => {
var listOfObjectIds = response.data;
var chain = Promise.resolve();
for (var objectId of listOfObjectIds) {
chain = chain.then(axios.get(`apiendpoint/${objectId}`)
.then((response) => {
objectDetail.push(response.data);
})
);
}
return chain;
}).then((chain) => {
console.log(chain);
return chain;
})
The code above is returning undefined as the promise chain object is not being passed to the then
method call. I'm wondering if my approach is incorrect or if there's something I'm overlooking. Thank you.
Here are some related articles that I've come across:
- How to loop dynamically over multiple promises in a for loop while using fetch?
- Creating a promise chain in a for loop