【发布时间】:2020-05-27 09:06:17
【问题描述】:
我在我的 Vue.js 应用程序中运行多个 axios.get() 调用。我想调用另一个函数
this.useData()
在所有提取都收到响应之后。我怎样才能做到这一点?我读过 Promise.all()。如果这对我有帮助,请告知如何将 Promise.all 合并到我的代码中。
fetchData() {
for (let j = 0; j < this.selectedLayers.length; j++) {
if (this.selectedLayers[j].foo == true) {
axios
.get("/maps")
.then(
response => {
console.log(
"received response for this.selectedLayers[" + j + "]"
);
this.selectedLayers[j].data= response.data;
},
error => {
console.log("error fetching data");
}
);
}
}
this.useData();
如果我将async 和await 添加到我的代码中,如下所示,Vue.js 会响应错误...
不能在异步函数之外使用关键字 'await'
await this.fetchData();
this.useData();
async fetchData() {
for (let j = 0; j < this.selectedLayers.length; j++) {
if (this.selectedLayers[j].foo == true) {
await axios
.get("/maps")
.then(
response => {
console.log(
"received response for this.selectedLayers[" + j + "]"
);
this.selectedLayers[j].data= response.data;
},
error => {
console.log("error fetching data");
}
);
}
}
看了论坛这里推荐的第一个答案后,我修改了我的代码如下...
fetchData() {
return new Promise(resolve => {
if (this.selectedLayers[j].foo == true) {
axios
.get("/maps")
.then(
response => {
console.log(
"received response for this.selectedLayers[" + j + "]"
);
this.selectedLayers[j].data= response.data;
},
error => {
console.log("error fetching data");
}
);
}
})};
let promises = [];
for (var i = 0; i < this.selectedLayers.length; i++) {
promises.push(this.fetchData(i));
}
Promise.all(promises)
.then(results => {
this.useData();
})
.catch(e => {
// Handle errors here
});
Promise.all() 永远不会执行。我想将 Promise.all() 与 axios.get() 结合使用会有细微差别?
【问题讨论】:
标签: vue.js asynchronous promise axios