简体   繁体   中英

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:

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'}
   ])

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: ...}];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM