简体   繁体   中英

Callback function on Vuejs

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM