Reputation: 21
I am trying to use async await to handle promises from buckets of requests (arrayOfArrays), however all of the requests are failing with Uncaught (in promise) 500 errors.
If I remove the bucket array (arrayOfArrays) and map directly over the original array of requests (stores) then the promises are handled correctly.
Is there a way to handle promises within multiple levels of Array.prototype.map() ?
let groupSize = 20
let arrayOfArrays = []
let newStoreRequests
let test
for (let i = 0; i < stores.length; i+=groupSize) {
arrayOfArrays.push(stores.slice(i,i+groupSize));
}
const getNewStoreRequests = async () => {
test = await Promise.all(
arrayOfArrays.map(async (arr) => {
arr.map(async ({ id, primary }) => {
return await axios.post(
`${REACT_APP_LAMBDA_ENDPOINT}/dummy/encrypted_hash=${hash}&api_key=${REACT_APP_LAMBDA_API_KEY}&build=dev-dummy`,
{
id: id,
store_id: storeId,
is_primary: primary,
}
);
})
})
)
}
getNewStoreRequests()
console.log('arrayOfArrays', arrayOfArrays)
console.log('newStoreRequests', newStoreRequests)
Original code that worked using the full array (The system would fail requests past the first 80~)
const newStoreRequests = await Promise.all(
stores.map(async ({ id, primary }) => {
return await axios.post(
`${REACT_APP_LAMBDA_ENDPOINT}/dummy?encrypted_hash=${hash}&api_key=${REACT_APP_LAMBDA_API_KEY}&build=dev-dummy`,
{
id: id,
store_id: storeId,
is_primary: primary,
}
);
})
);
Upvotes: 0
Views: 318
Reputation: 11600
No need to use async/await while mapping over arr
- you'll get the same result without it - an array of promises.
Also, arrayOfArrays.map
returns a bunch of undefined
wrapped in a promise.
it should be arrayOfArrays.flatMap(arr => arr.map(({...}) => axios.post(...)))
:
let groupSize = 20
let arrayOfArrays = []
let newStoreRequests
let test
for (let i = 0; i < stores.length; i+=groupSize) {
arrayOfArrays.push(stores.slice(i,i+groupSize));
}
const getNewStoreRequests = async () => {
test = await Promise.all(
arrayOfArrays.flatMap((arr) =>
arr.map(({ id, primary }) =>
axios.post(
`${REACT_APP_LAMBDA_ENDPOINT}/dummy/encrypted_hash=${hash}&api_key=${REACT_APP_LAMBDA_API_KEY}&build=dev-dummy`,
{
id: id,
store_id: storeId,
is_primary: primary,
}
)
)
)
)
}
getNewStoreRequests()
console.log('arrayOfArrays', arrayOfArrays)
console.log('newStoreRequests', newStoreRequests)
Upvotes: 1