1

I have the following Vue methods. When clicking on the edit button, onEditUserPermissions is called. That function also fetches this.fetchUserPermissions. The request does finish, and a response is received.

methods:{
  onEditUserPermissions(item){
    this.userCheckbox = true
    let user = item.id
    this.selectedUser = item.id;
    
    this.fetchUserPermissions(user)
    for (let x of this.assignedUserPermissions){
      console.log('assigned',x.id)
      this.selectedUserItems.push(x.id)
    }
    
    this.editedIndex =  'users'
    this.dialog = true
  },
  fetchUserPermissions(user){
    this.$axios.get('/permissions/assigned/user/'+user)
    .then(res => {
      this.assignedUserPermissions = res.data
    })
  },
}

When I first click, the for of loop doesnt work, it doesnt iterate, however, when clicked again, it works. I may be too close to the project but can anyone tell why?

Dan
  • 59,490
  • 13
  • 101
  • 110
chewie
  • 529
  • 4
  • 17
  • Please share more details - did you ensure that the request to the backend is finished before iterating over that array? – Nico Haase Feb 21 '21 at 12:56
  • @NicoHaase ok, I edited my question, but yes, the request finishes and a response is received. – chewie Feb 21 '21 at 12:59
  • My question was: how did you ensure that the request finishes **before** you iterate over that array? Axios is a promise-based client, so the method `fetchUserPermissions` does not wait for the response – Nico Haase Feb 21 '21 at 13:01
  • [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321) and [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086) – adiga Feb 21 '21 at 13:03

1 Answers1

1

You need to wait for the http promise to resolve before attempting to access the data. It works the second time because then it uses the result from the first fetch.

First, you need to return the promise from fetchUserPermissions, and then you need to wait for that promise in onEditUserPermissions:

methods: {
  async onEditUserPermissions(item){         // `async` keyword
    this.userCheckbox = true
    let user = item.id
    this.selectedUser = item.id;
    
    await this.fetchUserPermissions(user);   // awaiting the promise

    for (let x of this.assignedUserPermissions){
      console.log('assigned',x.id)
      this.selectedUserItems.push(x.id)
    }
    
    this.editedIndex = 'users';
    this.dialog = true    
  }

  fetchUserPermissions(user){
    return this.$axios.get('/permissions/assigned/user/'+user)  // return the promise
    .then(res => {
      this.assignedUserPermissions = res.data
    })
  },
}
Dan
  • 59,490
  • 13
  • 101
  • 110