Utilizing Vuejs for callback functions

I am attempting to ensure that a process runs synchronously. However, the presence of asynchronous Ajax calls has caused issues, resulting in my array being populated only after it is called. In order to overcome this obstacle, I am exploring the option of implementing a callback function. Unfortunately, I have not yet achieved success in resolving this issue.

Here is the snippet of code:

(the click action invokes this function):

VmUser.executa(user,this.addTodos)

The functions being executed:

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

Answer №1

Utilizing a Promise allows you to delay the execution of the `addTodos` method until an asynchronous request is completed.

I find it redundant that you are sending two requests to the endpoint `api/gethierarquia`. In your scenario, the implementation would likely resemble this:

execute(user, callback) {       
  this.setupTodos(user).then((response) => {
    this.addTodos(); // executes when the promise resolves
  }, (error) => {
    console.error(error); // handles promise rejection
  });
},

setupTodos(user) {
  return new Promise((resolve, reject) => {
    axios
      .get(`api/gethierarquia/${user.user_id}`)
      .then((response) => {
        // handle response data

        resolve(response); // if request was successful
      })
      .catch((error) => {
        reject(error); // if request failed
      });
  });
},

Answer №2

Let me break it down for you using a practical example that should make things clearer. Let's say you have a function as shown below:

const initKeys = (callback) => {
    const keys = useMagicKeys()
    const ctrlS = keys['Ctrl+S'] // save

    watch(ctrlS, (v) => {
      if(v){
        callback('click!')
      }
    })
}

You can then call this method within another function and observe the changes using the 'watch' functionality. I'll be demonstrating with Vue 3 in this scenario.

setup(props) {
// magic keys
    initKeys((k) => {
      console.log('pass ->', k);
    })
}

With this setup, you now have a basic callback from the initKeys function. Whenever there are changes to the 'ctrls', the callback function will be triggered during component initialization.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Interactive game created using JavaScript input

I've scoured the internet for guidance on creating a text-based game that utilizes user input, but all I come across are tutorials focusing on button interactions. What I envision is triggering different responses based on specific user inputs. For i ...

Unlock AngularJS expression through ng-click functionality

I've encountered an issue with accessing AngularJS expressions after a click event takes place. index.html <div class="row"> <a href="#/company"><div class="tile col col-comp cat-a-g grow-appear" ng-click="onSelect(item)" ng-repea ...

Generating a PDF file from HTML div content using a button click

I am looking to export a specific div section as a PDF file. The div contains a mix of text, images, and charts. <div id="newdiv"> <img src="http://imgsv.imaging.nikon.com/lineup/lens/zoom/normalzoom/af-s_dx_18-140mmf_35-56g_ed_vr/img/sample/ ...

The utilization of "startIcon" and "endIcon" from the <Button/> API of Material-UI is restricted

I've been trying to work with this React code for a single component, but no matter what I do, I keep getting the same warning. I even tried copying and pasting the example, but the warning persists and the icon is not showing up. Can someone please a ...

Is it possible to pass a router-view as a prop in Vue.js?

Can a prop be passed to another component when calling it? I have components and views, where I build my views using various components. I am looking for a way to create a reusable styled component, so I thought of creating a WebsiteLayout.vue: <templa ...

Why does the script run fine within the HTML but fails to work externally?

I recently created a script for my navigation bar that turns it into a sticky navigation once it reaches the top of the page. Everything works perfectly when I include the script directly in my index file using <script> tags. However, when I try to ...

Unable to display MongoDB collection in React application

I've been working on showcasing my projects using React and Meteor. I have two collections, Resolutions and Projects. The issue I'm facing is that while I can successfully display the Resolution collection on the frontend, I'm struggling to ...

Dynamically change the content of the DataTable by utilizing jQuery

I am facing an issue with updating a DataTable using jQuery when the contents of the table are modified. Initially, I have a HTML table with an empty tbody, which is populated dynamically based on selected filters such as select options. The table uses Dat ...

Capturing and postponing the javascript onsubmit event

I am currently utilizing a jQuery plugin that inserts placeholders into input fields for browsers that lack native support, and I'm attempting to implement it on a form with Asp.Net validation. Upon submitting the form, I clear out any placeholder va ...

Javascript - Displaying data retrieved from an external API with JSON

Seeking advice on how to effectively attach JSON values obtained from xhr.response to HTML labels. Any suggestions are appreciated. Thank you. On a different note, does anyone have recommendations for websites that provide concise explanations of basic JS ...

The positioning of the <a> tag seems to be slightly skewed

My goal was to add a simple dotted underline animation to the menu bar on my website, so I crafted the following HTML: <nav role="navigation" class="navigation"> <ul class="nav-listed-links"> <li class="active"><a href="">Ho ...

Manipulate and scale with jQuery

I am currently utilizing the jQueryUI library with its Draggable and Resizable functionalities to resize and drag a div element. However, I am encountering some unexpected behavior where the div jumps outside of its container upon resizing. How can I resol ...

How to eliminate the initial class with jQuery

I am encountering some issues with removing a class using jQuery. When I open a modal in Bootstrap, it generates code like this: <div class="modal-backdrop fade in"> in the footer. However, when I open a modal within another modal (2 modals), ther ...

How to style the currently active route link in Angular 2 using CSS

I want to add custom CSS styles to active router links: <a [routerLink]='link'>{{name}}</a> Here's what I attempted so far (Using the default router-link-active class): .router-link-active { color: #000; font-weight: bold; ...

Upon installation, the extension that replaces the new tab fails to detect the index.html file

edit: Check out the Chrome Extension here Edit 2: It seems that the recent update containing the index.html file was not published due to Google putting it under revision. Apologies for forgetting to include the index.html file in the upload zip, as I ...

Is there a way to access the 'created by' and 'updated by' fields in StrapiJS?

Recently diving into StrapiJS has been a rewarding experience overall, but a new challenge has presented itself. Upon inserting data into the database, I noticed that Strapi automatically generates certain fields like created_by and updated_by, yet these ...

Problem with Ionic App crashing

Currently, I am developing an Ionic app that relies on local storage for offline data storage. The app consists of approximately 30 different templates and can accommodate any number of users. Local storage is primarily used to store three key pieces of i ...

Difficulty in toggling on and off several form elements with JavaScript

Trying to control multiple form elements on an HTML page with JavaScript has presented a challenge for me. In my form, each row contains a checkbox that should enable/disable the elements on that row. The issue I'm facing is that only the first two f ...

Steps for updating the property "project_id" within a nested JSON array to "project_name"

Issue: [ { "project_id": 1, "project_name": "CDP", "role": "PL" }, { "project_id": 2, "project_name": "Admincer", "role": "PM" }, I am trying to extract the "project_id" property from the above JSON array and add it to another array using a specific ...

`I encountered some challenges while trying to integrate Firebase with my Vue.js application`

Currently, I am in the process of integrating Firebase into my Vue.js application. After setting up Vue.js using Vue CLI, installing firebase, vuefire, and bootstrap-vue, I attempted to retrieve data manually inserted into my database but encountered issue ...