I have this array of objects
const items = [
{
quantity: '2',
name: 'john',
type: 'https://api/event/1',
},
{
quantity: '3',
name: 'jane',
type: 'https://api/event/2',
}
]
for each object in the array, I need to call the API n number of times depending on the object quantity value. Calling the API will basically generate a unique link. I know this is not the best for performance but this is a small app and we'd be making between 3-5 api calls in the worst case scenario, usually 1 tbh. In this case, I have 2 objects in the array, the first has 2 API calls and the second has 3 API calls. Every time I call the API I want to save the result (unique link) in an array so that I can email them to the customer who bought them.
This is what I have tried so far but it hasn't worked:
const promises = []
const getLinks = async (arr) => {
for (var i = 0; i < arr.length; i++) {
for (var j = 0; j < arr[i].quantity; j++) {
const getLink = (owner) => {
axios.request({
method: 'POST',
url: 'https://api.call'
})
.then(function (response) {
const promise = response.data.url
promises.push(promise)
})
.catch(error => console.log(error))
}
}
}
const links = await Promise.all(promises)
console.log('links:', links) // === [] this is always empty ===
}
getLinks(items)
One thing I learned is that await cannot be and will slow down the code drastically inside loops
I can't seem to get it to work