同时获取多个 URL?

use*_*820 5 javascript fetch vue.js

我正在寻找一种同时获取多个 URL 的方法。据我所知,API 只能通过单个产品查找来检索我想要的数据,因此我需要使用 url 结构“/products/productID/”一次获取多个产品。注意,这是在 VUEJS 中。这是我的代码到目前为止的样子:

在我的 productServices.js 中:

const productsService = {
 getCategory(productID){
    const url = `${config.apiRoot}/products/${productID}`

    return fetch(url, {
    method: 'GET',
    headers: {
        'content-type': 'application/json',
        'Authorization': `Bearer ${authService.getToken()}`
    },
    })
 }
}
Run Code Online (Sandbox Code Playgroud)

在我看来:

data() {
  return {
    featuredProduct: [13,14,15],
    productName: [],
    productImg: []
  }
}
Run Code Online (Sandbox Code Playgroud)
async mounted(){
    const response = await productsService.getCategory(this.featuredProduct)
    const resJSON = JSON.parse(response._bodyInit)
    this.loading = false
    this.productName = resJSON.name
    this.productImg  = resJSON.custom_attributes[0].value
}
Run Code Online (Sandbox Code Playgroud)

所以我需要点击所有三个特色产品 ID 并存储数据。我不太确定如何遍历多个 URL。我所有的其他 API 调用都可以使用搜索参数轻松获得所有数据,但对于我在此处需要的特定数据(产品图片),只能通过调用单个产品来查看。

任何帮助深表感谢!

Eli*_*ias 10

就像里卡多建议我使用Promise.all. 一旦所有传递的承诺都完成,它接受一组承诺并解析返回的承诺(它以数组的形式解析承诺,其中结果与请求的顺序相同)。

文档

Promise.all([
  fetch('https://randomuser.me/api/').then(resp => resp.json()),
  fetch('https://randomuser.me/api/').then(resp => resp.json()),
  fetch('https://randomuser.me/api/').then(resp => resp.json()),
  fetch('https://randomuser.me/api/').then(resp => resp.json()),
  fetch('https://randomuser.me/api/').then(resp => resp.json())
]).then(console.log)
Run Code Online (Sandbox Code Playgroud)

使用map+ Promise.all (已测试)

Promise.all([1, 2, 3].map(id => 
  fetch(`https://jsonplaceholder.typicode.com/todos/${id}`).then(resp => resp.json())
)).then(console.log);
Run Code Online (Sandbox Code Playgroud)

如果数组中有多个产品需要获取,则可以使用:

代码未测试

Promise.all(productIds.map(productId => 
  fetch(`https://url/products/${productId}`)
)).then(() => {/* DO STUFF */});
Run Code Online (Sandbox Code Playgroud)

关于存储数据的小建议:

如果您将所有内容都存储在一个数组中,那么整个工作就会变得更容易。所以你可以这样做

fetchFunction().then(results => this.products = results);

/*
  this.products would then have a structure something like this:
  Array of Obejcts: {
    name: "I'm a name",
    displayName: "Please display me",
    price: 10.4
    // And so on
  }
*/
Run Code Online (Sandbox Code Playgroud)


Dav*_*don 3

因为您有一系列产品,所以我首先更改您的州名:

data() {
  return {
    productIds: [13, 14, 15],
    productNames: [],
    productImages: [],
  };
},
Run Code Online (Sandbox Code Playgroud)

然后你可以使用Promise.all并行获取产品:

async mounted() {
  const responses = await Promise.all(
    this.productIds.map(id => productsService.getCategory(id))
  );
  responses.forEach((response, index) => {
    const resJSON = JSON.parse(response._bodyInit);
    this.productNames[index] = resJSON.name;
    this.productImages[index] = resJSON.custom_attributes[0].value;
  });

  this.loading = false;
}
Run Code Online (Sandbox Code Playgroud)

您还可以考虑重构getCategory为您进行解析并返回一个包含 aname和 an 的对象image- 这样,mounted就不必了解内部响应结构。