同时获取多个 URL?

新手上路,请多包涵

我正在寻找一种同时获取多个 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()}`
    },
    })
 }
}

在我看来:

 data() {
  return {
    featuredProduct: [13,14,15],
    productName: [],
    productImg: []
  }
}

 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
}

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

任何帮助深表感谢!

原文由 user3330820 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 844
2 个回答

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

 data() {
  return {
    productIds: [13, 14, 15],
    productNames: [],
    productImages: [],
  };
},

然后您可以使用 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;
}

You could also consider refactoring getCategory do the parsing for you and return an object containing a name and an image - that way, mounted 不必了解内部响应结构。

原文由 David Weldon 发布,翻译遵循 CC BY-SA 4.0 许可协议

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

文档

 Promise.all([
  fetch('https://jsonplaceholder.typicode.com/todos/1').then(resp => resp.json()),
  fetch('https://jsonplaceholder.typicode.com/todos/2').then(resp => resp.json()),
  fetch('https://jsonplaceholder.typicode.com/todos/3').then(resp => resp.json()),
]).then(console.log)

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

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

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

代码未测试

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

关于存储数据的小建议:

如果你把所有东西都存储在一个数组中,它会让整个工作变得更容易。所以你可以做

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
  }
*/

原文由 Elias 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题