我有一个名为“ urls”的对象数组,其中包含每个具有“ name”和“ url”属性的对象。我想将每个对象映射到一个数组。我该如何实现?
let urls = [{
"name": "regions",
"url": context + "ip/region/getAllRegions.do?query="
},
{
"name": "sub regions",
"url": "context + 'ip/region/getAllSubRegions.do"
},
];
this.axiosData = urls.map(t => {
axios.get(t.url)
.then(res => {
if (res.data.responseCode == 1) {
return res.data.payload;
} else {
toastr.error("error retrieving " + t.name, "Failure");
}
})
.catch(err => {
console.log(err);
});
});
此处res.data.payload将是一个对象数组,axiosData在Vue实例的属性内的数据中定义。我希望作为数组的'axiosData'是对象数组的数组。
axiosData可能是这样的:
[[{
"id": 8,
"name_en": "Rangpur",
}, {
"id": 9,
"name_en": "Sylhet",
}, {
"id": 10,
"name_en": "Mymensingh",
}],
[{
"another_id": 8,
}, {
"another_id": 9,
}, {
"another_id": 10,
}]]
答案 0 :(得分:2)
您应该使用Promise.all函数来发出多个请求。
let urls = [{
"name": "regions",
"url": context + "ip/region/getAllRegions.do?query="
},
{
"name": "sub regions",
"url": "context + 'ip/region/getAllSubRegions.do"
},
];
this.axiosDataPromises = urls.map(t => {
return axios.get(t.url)
.then(res => {
if (res.data.responseCode == 1) {
return res.data.payload;
} else {
toastr.error("error retrieving " + t.name, "Failure");
}
})
.catch(err => {
console.log(err);
});
});
Promise.all(this.axiosDataPromises).then(resultArr => {
this.axiosData = resultArr;
})