Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to send n axios post requests depending on number of elements in array

I have a params object:

const params = {price: '5000', qty: ''}

I have an array:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const sizes = [2, 3, 4, 5]

How can I make a params object for each element in the array and then use each object to make an axios request with number of requests depending on the number of elements in the array?

The array will vary. Sometimes it will have 4 or elements, or 10, or 20. I think the structure should look like the below sample, but it will vary depending on the size of the array.

   const [
     { data: data1 },
     { data: data2 },
     { data: data3 },
     { data: data4 },
   ] = await Promise.all([
     axios.post(url, params), // const params = {price: '5000', qty: '2'}
     axios.post(url, params), // const params = {price: '5000', qty: '3'}
     axios.post(url, params), // const params = {price: '5000', qty: '4'}
     axios.post(url, params), // const params = {price: '5000', qty: '5'}
   ])

>Solution :

See {...params, qty: size}, this part makes qty equal to each item in the array. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map for more info on array mapping and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax for info on the ... operator (or spread operator).

const sizes = [2, 3, 4, 5];
const response = await Promise.all(sizes.map(size => axios.post(url, {...params, qty: size}));
const datas = response.map(res => res.data); // [{data: ...}, {data: ...}];
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading