[Vuejs]-Using Promise.all to execute a function after loop for

0👍

I would avoid writing async/await and promise functions in the same function… it makes it a little confusing to follow as you can see.

In this case I have rewritten it (not tested) as an example as how I would separate the promise generation (for parallel processing) from your async/await syntax.

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.');
  }
}

Leave a comment