1

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)
                })  
              }
            })
        })
      }
    })
},

2 Answers 2

3

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
      });
  });
},
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks man, but did not solve my problem ... I do not know why, but the last function is not triggered.
what do you mean "last function"?
this.addTodos()
Is the request failing? In my simplified code, addTodos will get called unless the request fails
I have two ajax requests because the purpose is to build a list of users. I have the first level where it is a director, for the director I have several supervisors (First requisition) and for each supervisor I have several employees (second requisition). It works. But after I have the array set up with all the officers (Directors, Supervisors and Officials) I need to display on the screen. This last part of screen display that does not happen. Execute via callback, is precisely because it can only be displayed on the screen once the process of filling it is completed.
|
-1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.