Reputation: 71
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)
})
}
})
})
}
})
},
Upvotes: 1
Views: 20304
Reputation: 1886
I explain to you by using my sample, i think this is quite easy to understand. Suppose you have a function like below
const initKeys = (callback) => {
const keys = useMagicKeys()
const ctrlS = keys['Ctrl+S'] // save
watch(ctrlS, (v) => {
if(v){
callback('click!')
}
})
}
Then you can call this method in another function and try to listen the watch. I use vue3 in this case
setup(props) {
// magic keys
initKeys((k) => {
console.log('pass ->', k);
})
}
Now you have a simple callback from function initKeys
. Whenever ctrls
make changes it would triggers callback function to the component initialize.
Upvotes: -1
Reputation: 55664
You can use a Promise to wait until the asynchronous request is finished to call the addTodos
method.
I'm not sure why you are making two requests to api/gethierarquia
. However, I think in your case it would look something like this:
executa(user, callback) {
this.montaTodos(user).then((response) => {
this.addTodos; // gets here when the promise is resolved
}, (error) => {
console.error(error); // gets here when the promise is rejected
});
},
montaTodos(user) {
return new Promise((resolve, reject) => {
axios
.get(`api/gethierarquia/${user.cod_usuario}`)
.then((response) => {
// logic to handle response
resolve(response); // the request was successfull
})
.catch((error) => {
reject(error); // the request failed
});
});
},
Upvotes: 3