我正在尝试在循环结束时执行函数exportList()。 但是函数执行不等待周期结束。 执行函数exportList()时,对this.ExportList数组不完整。
async getUser() {
let promsArr = [];
for (let i = 0; i < this.User.length; i++) {
let requestUri = `domain/GetPropertiesFor(accountName=@v)?@v='${this.User[i].login}'`;
let prom = axios
.get(requestUri, {
headers: {
Accept: "application/json;odata=verbose"
}
})
.then(response => {
let props = {};
let d = response.data.d;
let department, email = "";
if (d.UserProfileProperties.results.length > 0) {
for (var i = 0; i < d.UserProfileProperties.results.length; i++) {
if (d.UserProfileProperties.results[i].Key === "Department") {
department = d.UserProfileProperties.results[i].Value;
}
}
}
props = {
dep: department,
email: d.Email
};
promsArr.push(prom);
this.ExportList.push(props);
})
.catch(error => {
console.log(error);
});
}
await Promise.all([promsArr]).then(this.exportList())
}
答案 0 :(得分:0)
我会避免在同一函数中编写async / await和promise函数……这使您难以理解。
在这种情况下,我将其重写(未经测试)作为示例,说明了如何将promise生成(用于并行处理)与您的async / await语法分开。
async getUser() {
const processResponse = function(response){
let props = {};
let d = response.data.d;
let department, email = "";
if (d.UserProfileProperties.results.length > 0) {
for (var i = 0; i < d.UserProfileProperties.results.length; i++) {
if (d.UserProfileProperties.results[i].Key === "Department") {
department = d.UserProfileProperties.results[i].Value;
}
}
}
props = {
dep: department,
email: d.Email
};
return props;
};
const getAccountProps = function(login){ // this function returns a promise!
let requestUri = `domain/GetPropertiesFor(accountName=@v)?@v='${login}'`;
return axios
.get(requestUri, {
headers: {
Accept: "application/json;odata=verbose"
}
})
.then(processResponse);
};
try{
let promsArr= this.User.map(u=>getAccountProps(u.login));
let propsArr = await Promise.all(promsArr);
this.ExportList.push(propsArr);
await this.exportList();
}catch(e){
console.log('An error occurred while getting all account properties.');
}
}