Axios.all多次调用来自具有多个链接的阵列的请求



data1是一个数组,包含来自以下循环的5个链接。

let data1 = [];
console.log(data1);
for (let Items of ItemsArray) {
const row = {
PricingSummary: Items.pricingOptionsSummaryUrl,
}
data1.push(row);
};

我想使用这个数组通过Axios.all执行5次GET请求
在得到响应后,我想设置State以映射我想要的数据。

const callprice = () => { //assign a variable for a call function
Axios.all(data1.map(l => Axios.get(l)))
.then(Axios.spread(function(...res) {
// setStats(....)
console.log(res); // Getting error message : xhr.js:210 GET http://localhost:3000/[object%20Object] 404 (Not Found)
}));
};

我得到localhost 404(未找到(错误。相信来自data1的请求数组链接不正确,但不确定如何使其正确

data1控制台示例:

0: {PricingSummary: 'http://snapshot.dellsvc/snapshots/MXL5hLvzBkajQ-fqGTo9oA'}
1: {PricingSummary: 'http://snapshot.dellsvc/snapshots/3gmDYxoCg0m9YgWB3aLLpA'}
2: {PricingSummary: 'http://snapshot.dellsvc/snapshots/dEpCHAi3IUe1sTIqEo9Idw'}
3: {PricingSummary: 'http://snapshot.dellsvc/snapshots/SAIS_lcIxU202-Mnm5KLIQ'}
4: {PricingSummary: 'http://snapshot.dellsvc/snapshots/H_9txy3Ejkm-zoe49Hbkzg'}
5: {PricingSummary: undefined}

首先,不赞成使用axios.all()axios.spread()。您应该使用Promise.all((或Promise.allSettled((。

其次,您的URL中似乎至少有一个是undefined,这在请求中肯定不起作用。您可能需要筛选出这些问题记录。

第三,将具有PricingSummary属性的对象推送到data1中。这些不能在axios.get()中使用,因为它需要一个URL字符串,而不是一个对象。这就是[object%20Object]的来源。

const callprice = async () => {
const responses = await Promise.all(
ItemsArray
.filter(item => item.pricingOptionsSummaryUrl) // remove falsy values
.map(async (item) => (await axios.get(item.pricingOptionsSummaryUrl)).data) 
)
// now `responses` is an array of the response data
}

您应该使用Promise.allSettled而不是

最新更新