I am trying to make a process run in a synchronous way. However, as I have ajax calls, which are naturally asynchronous, I'm having problems because my array is only populated after it has been called. To solve this problem, I'm trying to do a callback function. But I'm not having success.
Here's my code:
(click action calls this function):
VmUser.executa(user,this.addTodos)
The functions that are called:
executa(user, callback) {
this.montaTodos(user, { complete: callback })
},
addTodos() {
const VmUser = this
VmUser.details = VmUser.todos.map(user => {
VmUser.$bus.$emit('add-user', { user: user })
})
},
montaTodos(user) {
const VmUser = this
axios
.get(`api/gethierarquia/${user.cod_usuario}`)
.then(res => {
if (res.data.usuarios.length !== 0){
//VmUser.$bus.$emit('add-user', { user: user})
VmUser.todos.push(user)
VmUser.supervisores = res.data.usuarios
VmUser.details = VmUser.supervisores.map(user => {
VmUser.todos.push(user)
axios
.get(`api/gethierarquia/${user.cod_usuario}`)
.then(res => {
if (res.data.usuarios.length !== 0){
VmUser.funcionarios = res.data.usuarios
VmUser.details = VmUser.funcionarios.map(user => {
VmUser.todos.push(user)
})
}
})
})
}
})
},