简体   繁体   English

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

[英]Multiple call of Axios.all requests from an array with multiple links

data1 is an array with 5 links from the below loop. data1是一个数组,其中包含来自以下循环的 5 个链接。

let data1 = [];
console.log(data1);

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

I want to use this array to perform 5 times GET requests by using Axios.all .我想使用这个数组通过使用Axios.all来执行 5 次 GET 请求。
After getting the response, I want to setState to map with the data I want.得到响应后,我想用我想要的数据将状态设置为 map。

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)
    }));
};

I'm getting the localhost 404 (Not Found) errors.我收到 localhost 404(未找到)错误。 Believe the request array links are incorrect from the data1 , but not sure how to make them correct.相信data1中的请求数组链接不正确,但不知道如何使它们正确。

Example of the console for the 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}

First, axios.all() and axios.spread() are both deprecated .首先, axios.all()axios.spread()都已弃用 You should use Promise.all() or Promise.allSettled() instead.您应该改用Promise.all()Promise.allSettled()

Second, it seems at least one of your URLs is undefined which definitely won't work in a request.其次,您的 URL 似乎至少有一个undefined ,这在请求中肯定不起作用。 You may want to filter out these problem records.您可能希望过滤掉这些问题记录。

Third, you're pushing objects with a PricingSummary property into data1 .第三,您将具有PricingSummary属性的对象推送到data1中。 These cannot be used in axios.get() since it expects a URL string , not an object.这些不能在axios.get()中使用,因为它需要 URL字符串,而不是 object。 This is where your [object%20Object] is coming from.这就是您的[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
}

You shoud use Promise.allSettled instead您应该改用 Promise.allSettled

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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