Vue: Ensuring one method finishes executing before triggering the next one

I've implemented two methods in my Vue instance;

const app = new Vue({
  el: '#app',
  data: {
   id: null
  },
  methods: {
   getId: function() {
     return axios.get('url')
     .then(response => response.data)
     .then(id => this.id = id)
     .catch(error => console.log(error))
   },

   foo: function() {
    console.log(this.id)
   }
 },
 mounted: function() {
 this.getId()
 this.foo()
 }
})

The console.log() displays null because it executes before the response from getId() has a chance to set the id value. This can be observed using the Vue developer tools, where the id is correctly displayed rather than as null.

Is there a way to ensure that getId() sets the value before calling this.foo()?

Answer №1

If you want to achieve this, one approach is using JavaScript promises. The async/await syntax provides a straightforward way to do it.

const app = new Vue({
  el: '#app',
  data: {
   id: null
  },
  methods: {
   getId: function() {
     return axios.get('url')
     .then(response => response.data)
     .then(id => this.id = id)
     .catch(error => console.log(error))
   },

   foo: function() {
    console.log(this.id)
   }
 },
 mounted: async function() {
   await this.getId()
   this.foo()
 }
})

Alternatively, you can opt for the traditional method as well.

const app = new Vue({
  el: '#app',
  data: {
   id: null
  },
  methods: {
   getId: function() {
     return axios.get('url')
     .then(response => response.data)
     .then(id => this.id = id)
     .catch(error => console.log(error))
   },

   foo: function() {
    console.log(this.id)
   }
 },
 mounted: function() {
   this.getId().then(() => this.foo())
 }
})

Answer №2

Discover numerous possibilities by exploring different avenues. I recommend delving into Promises in JS for an enlightening experience. However, a straightforward answer can be provided here:

const app = new Vue({
  el: '#app',
  data: {
   id: null
  },
  methods: {
       getId: function(callback) {
         return axios.get('url')
         .then(response => response.data)
         .then((id) => { 
               this.id = id
               callback()
          })
         .catch(error => console.log(error))
       },

       foo: function() {
        console.log(this.id)
       }
  },
  mounted: function() {
     this.getId(() => {
        this.foo()
     })
  }
})

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

A guide on adjusting a function to pause execution until a line is complete

In the code snippet below, there is an angularJS function named myFunc: $scope.myFunc = () => { myModule.getConfig().update(params); myModule.go(); myModule.log('ok'); }; Additionally, there is a go function defi ...

What is the best way to remove a selected item from an array in Vuejs when it has been clicked

I'm having trouble with my splice() method in this simple To-Do app. I want to delete a specific task by clicking a button, but the solutions I've tried from Stack Overflow aren't working for me. The items do get deleted, but only the last o ...

Uploading files with the help of Formik and the Material-UI stepper component

When attempting to upload a file, the entire component refreshes each time. The process involves 3 steps: the first step captures the user's name, the second step collects their address, and the third step allows them to upload a profile picture. Howe ...

Leveraging NextJS to perform server side rendering by injecting parameters from a caller component

I'm currently in the process of creating an application with a storefront using nextJS. I've successfully utilized getServerSideProps when loading a new page. This particular page is quite complex, as it consists of multiple components, each req ...

Downloading PDF files on IOS while using Angular often results in the PDF opening in the same

I'm currently utilizing file-saver within my Angular application to retrieve a PDF generated from the backend. The library functions smoothly on desktop and Android devices, but I'm encountering issues with downloading files on iOS. Contrary to w ...

Can you explain the variation between a standard javascript integer and one obtained from jquery.val()?

Utilizing a script known as countUp.js, I am able to increment an integer in a visually appealing manner until it reaches the desired value. This is how I have implemented the code: HTML: <h2 id="countUp-1">2500</h2> JS var theval = 5000; va ...

Preventing access to drives and desktop until the mandatory HTML form is completed

Looking to develop a webpage in JSP that will automatically open whenever my system is started. Users will be required to fill out a form on this page before proceeding further. If they attempt to bypass filling out the form, they should not have access ...

Having trouble locating the bootstrap import statement

Currently, I am working on a project in Angular where I have defined two styles in the angular.json file - styles.css and node_modules/bootstrap/dist/css/bootstrap.min.css. After running ng serve, it shows that it compiled successfully. However, upon ins ...

JavaScript function to close mobile menu when menu item is clicked

https://i.sstatic.net/GfKem.png I have a dilemma with my HTML code. I am trying to figure out how to collapse the menu when clicking on a menu item using JavaScript. I have been stuck on this for two days now. Can anyone provide a solution with an explanat ...

Is it possible for AJAX to access files with unique extensions?

I recently discovered some files with the extension .cst on my localhost server. I'm wondering if AJAX is capable of loading them. So, here's my question: Can AJAX load files with custom extensions? If yes, how can I achieve this? If not, is ther ...

Using PHP functions in an AJAX request

I am currently attempting to execute a php loop upon clicking a radio button. I understand that ajax is necessary for this task, but as a beginner in ajax, I am struggling to achieve the desired result. Presently, I am unable to click the radio button at a ...

Pause and continue scrolling through the page with the push of a button

I have a question about a simple demo. I am looking to prevent scrolling when button1 is clicked, and then resume scrolling when button2 is clicked. Can someone guide me on how to achieve this? Check out the Fiddle here HTML: <input type='button& ...

Continuous Scrolling with Callback Function in jQuery

I have implemented the infinite-scroll plugin, which replaces traditional pagination with ajax to fetch new pages. The issue I am facing is that jQuery functions do not recognize the new posts, causing certain functions like the ones below to stop working ...

Unable to retrieve data from the JSON object

I'm struggling to extract the data value from a JSON object. Let me share my code snippet: var ab_id = $( "#ab_id" ).val(); $.ajax({ type: 'GET', contentType: 'application/json', url: 'edit_account.php', ...

What is the process for obtaining all of the options from a jQuery datepicker in order to create a new datepicker with identical settings?

Is there a way to easily replicate all options of a jQuery datepicker when creating a new instance? I am trying to duplicate a table that includes 2 datepickers with different settings. For reference, you can view an example here: http://jsfiddle.net/qwZ5 ...

HTML and JavaScript - Facing issues rendering HTML content during the conversion process from Markdown format

In this particular scenario, my goal is to transform the content inside #fileDisplayArea into markdown format. However, I am encountering an issue where the HTML code within the div element is not being rendered. <div id="fileDisplayArea"># Title ...

How can we ensure that Protractor's ElementArrayFinder 'each' function pauses until the current action has finished before moving on to the next iteration?

Currently, I am facing an issue while trying to utilize an 'each' loop in my Angular 8 app's end-to-end tests using protractor. Within my page object, I have created a method that returns an ElementArrayFinder. public getCards(): ElementArr ...

Modify the button input value within a PHP script

I am currently working on a piece of code that involves following different users and inserting values from a MySQL table. <td align="center"> <input type="button" name="<?php echo $id; ?>" id="<?php ech ...

Add a npm module without type definitions

I am currently utilizing Typescript version 2.1 and facing an issue with installing an npm package called 'reactable' that lacks typings. When attempting to import the package using import * as Reactable from 'reactable', Typescript di ...

The ZIP file downloaded from NodeJS is corrupted and cannot be opened

Currently, I am utilizing the following code to create a MySQL dump in memory, then zip that SQL file with a password from memory and save it to the hard drive so it can be streamed to the client... /* DUMP - database */ var mysqld ...