Javascript 同时获取多个URL?

Javascript 同时获取多个URL?,javascript,vue.js,fetch,Javascript,Vue.js,Fetch,我正在寻找一种同时获取多个URL的方法。据我所知,API只能通过单个产品查找检索我想要的数据,因此我需要使用url结构“/products/productID/”一次获取多个产品。注意,这是在VUEJS中实现的。到目前为止,我的代码是这样的: 在my productServices.js中: const productsService = { getCategory(productID){ const url = `${config.apiRoot}/products/${produc

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

在my 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: []
  }
}
所以我需要点击所有三个FeaturedProductID并存储数据。我真的不知道如何在多个URL之间循环。我的所有其他API调用都有使用搜索参数随时可用的所有数据,但对于我在这里需要的特定数据(产品图像),只能通过调用单个产品来查看


非常感谢您的帮助

检查
承诺。所有


也许你可以通过迭代你的
数据来创建你需要的调用,然后批量请求它们。

因为你有一系列产品,我首先要更改你的州名:

data(){
返回{
productId:[13,14,15],
产品名称:[],
productImages:[],
};
},
然后,您可以使用来并行获取产品:

async-mounted(){
const responses=等待承诺(
this.productIds.map(id=>productsService.getCategory(id))
);
响应。forEach((响应,索引)=>{
const resJSON=JSON.parse(response.\u bodyInit);
this.productNames[index]=resJSON.name;
this.productImages[index]=resJSON.custom_属性[0]。值;
});
这一点:加载=错误;
}

你也可以考虑重构<代码> GETCype < /代码>对你进行解析并返回一个包含<代码>名称>代码>和<代码>图像>代码>的对象,即“代码>安装/ <代码>不必知道内部响应结构。

< P>如建议我将使用<代码>承诺>所有< /代码>。它接受一个承诺数组并解析承诺一旦所有传递的承诺都完成,它将返回(它以数组的形式解析承诺,其中结果的顺序与请求的顺序相同)

Promise.all([
取('https://randomuser.me/api/,然后(resp=>resp.json()),
取('https://randomuser.me/api/,然后(resp=>resp.json()),
取('https://randomuser.me/api/,然后(resp=>resp.json()),
取('https://randomuser.me/api/,然后(resp=>resp.json()),
取('https://randomuser.me/api/)。然后(resp=>resp.json()

]).then(console.log)
在Angular中,有一个
forkJoin
方法通过同时发送多个请求来获取结果,直到最后一个结果出现。您可以在VueJS中研究
forkJoin
。感谢您的响应,但是我现在收到以下错误:[Vue warn]:挂载挂钩中的错误(承诺/异步):“SyntaxError:JSON中位于位置0的意外标记u”,这表示响应返回未定义。很抱歉,我输入了一个错误。请查看更新的代码。如果这不起作用,请在
forEach
循环中放置一个控制台日志,以查看返回的内容。谢谢,看起来这就成功了。这正是我想要的。谢谢你的回复,下面的答案很好,但这也是一个很好的信息。我同意,将数据存储在一个数组中最有意义。这是我的下一步,只是想确保抓取工作正常。谢谢@user3330820好的,很高兴你找到了你想要的:)
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
}