Do watches operate asynchronously?

I am monitoring the status of a variable called radioStatus within a Vue instance:

watch: {
    radioStatus: function(val) {
      if (!this.discovery) {
        $.ajax({ url: '/switch/api/radio/' + (val ? 'on' : 'off') })
      }
    }

This variable may be updated during an AJAX call triggered upon page refresh:

$.ajax({
  url: "/api",
  cache: false
})
  .done(function(response) {
    vm.discovery = true;
    vm.radioStatus = response.radio.ison;  // <-- the change I mention below is here
    vm.discovery = false;
  });

Is it safe to assume that all functions triggered by a change in radioStatus will complete before moving on to the next line (vm.discovery = false)?

My concern lies in the fact that vm.discovery serves as a flag for multiple watched variables (similarly to radioStatus), and it may switch states before the functions related to the watched variables are fully executed.

Answer №1

Indeed, watchers work asynchronously. Reference: https://vuejs.org/guide/computed.html#Watchers

A snippet from the mentioned source:

Watchers

While computed properties are... This is particularly helpful when dealing with asynchronous or resource-intensive tasks triggered by data changes.

In the scenario you described, the vm.discovery = false; operation will be carried out before entering the watch. By setting vm.discovery to false, the ajax call inside radioStatus will consistently execute.

To address this issue, you might consider utilizing vm.$nextTick() as outlined below:

$.ajax({url: "/api", cache: false})
    .done(function(response) {
        vm.discovery = true;
        vm.radioStatus = response.radio.ison;
        vm.$nextTick( () => {
            console.log("Setting vm.discovery to false");
            vm.discovery = false;
        });
    });

It's a complex task to handle - because your callback for radioStatus() in watch will also occur within the nextTick context. Assuming the watch is triggered by the previous line (vm.radioStatus = ...), technically it should be queued first and thus completed sooner. To verify this, you may need to include several console.log statements.

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

Using ThreeJS in conjunction with NextJS requires that class constructors be called with the 'new' keyword

Seeking assistance with rendering a basic scene within a nextJS route named "lab2". Encountering the following error: Error: class constructors must be invoked with 'new' Call Stack: renderWithHooks mountIndeterminateComponent ...

sort the array based on its data type

Recently diving into typescript... I have an array that is a union of typeA[] | typeB[] but I am looking to filter based on the object's type interface TypeA { attribute1: string attribute2: string } interface TypeB { attribute3: string attri ...

Is it possible to host static files alongside running an API on the server?

As a newcomer to web development, I find myself in unfamiliar territory as my friend and I delve into a project involving Vuejs, jade, stylus, and jeet. The combination of all these frameworks is overwhelming, especially since there seems to be no clear ex ...

Tips for efficiently expanding NodeJS while running it through an Apache web server?

Currently, I have Apache Web Server running alongside NodeJS on the same system but on different ports. I am reverse proxying to connect and use them for various purposes. My concern is how to scale this architecture up to accommodate around 10 million u ...

Creating a dropdown menu in AngularJS using the ng-repeat directive

I have recently started working with AngularJS. I am trying to create three tickets using ng-repeat, each containing a dropdown list to select the number of tickets. However, I am facing an issue where the selected number is not displaying in the span. Can ...

Create an AngularJS directive that formats the model value for visual display, while retaining the original value in the model

I am facing a challenge in building an AngularJS directive for a currency textbox. The directive should take values (amount and currency code) from the model in the scope and then apply currency formatting to it. I am struggling to build this directive usi ...

Is there a versatile spell-checking tool available for HTML text boxes?

When designing a text box in HTML, I want to provide real-time input validation and spell check for the user's text. My goal is to underline any spelling mistakes as they type. This seems like a basic feature, but I've yet to find a plugin or AP ...

Having trouble with the scrollbar appearance after updating Chrome?

I've encountered an issue with my code after the latest Chrome update. Is there a way to implement cross-browser styling for scrollbars? // Looking for Scrollbar Styling Solution const scrollbarStyle = { scrollbarColor: `${themeLayers.scrollBar[0 ...

One controller, divergent template, introducing a fresh variable

I have a webpage where I showcase data (www.mysite.com/:gameId). In order to create a printer-friendly version of this data, I've set up a print page at www.mysite.com/:gameId/print. Both pages display the same information but with different designs. ...

In Node.js, JavaScript, when using SQLite, the variables are inserted as Null

I have spent a lot of time searching and trying various methods, but I am still unable to solve this issue. My goal is to insert 8 variables received from an API call into an SQLite table. Although the execution seems correct, when I query the table, all v ...

The jQuery toggle function seems to be skipping alternate items

I have recently started learning Javascript and JQuery. Currently, I am working on creating a comment system where you can click reply to display the form. However, I'm facing an issue where the form only shows up for the first comment reply, not for ...

The error message states that there is a missing parent component for <MenuItems /> with the <Menu /> component in the slot

Currently, I am in the process of developing a custom Vue3 component known as <Dropdown>. This particular Dropdown component relies on several other components including: Menu, MenuItems, MenuItem, and MenuButton from the headlessui/vue library. Th ...

Struggling to display the Three.js LightMap?

I'm having trouble getting the lightMap to show on my mesh. Here's the code I'm using: loader.load('model.ctm', function (geometry) { var lm = THREE.ImageUtils.loadTexture('lm.jpg'); var m = THREE.ImageUtils.loadT ...

Alter the functionality of the input element that has a tag of 'multiple'

I am encountering an issue with a form that allows users to upload multiple photos. When selecting multiple files at once, everything works as expected. However, if a user wants to add images one by one, each new addition deletes the previous file due to t ...

Display a text box upon clicking an item

I've been curious about how to create the effect of a text box or div that appears when clicked on, similar to what you see in this. Scroll down and click on "show patchnotes"; I've been puzzled by this for a while but haven't come across a ...

When using Vue.js, it is not possible to quote variables in HTML element attributes

Below is the provided code snippet: <tr v-for="(item, index) in detail" :key="item.name" class="[[ item.name ]]"> <td>[[ index + 1 ]]</td> <td>[[ item.name ]]</td> The resulting HTML output i ...

Customize the size of innerWidth and innerHeight in your THREEjs project

Is there a way to customize the size of the window where this function launches instead of it automatically calculating the height and width? I've attempted to modify this section of the code, but haven't had any success so far: renderer.setSiz ...

Vuejs error: Attempting to access properties of undefined

In my Vue table, I have select options. However, an error occurs when a group is not associated with a machine, which should not happen. The goal is for only "-" to appear in this case. This error is logged in the console and causes the DataTable not to di ...

There was a syntax error found in the JSON input when $.ajax() was utilized, resulting in

I'm currently working on a website that requires implementing a chat feature. The project is running locally, but I've encountered an error: SyntaxError: Unexpected end of JSON input Despite searching online for a solution, nothing seems to w ...

Javascript for Cordova utilizing WebSocket and incorporating client side certificates

I am looking to establish a secure SSL/TLS connection between my client and server, with only a specific authorized client allowed to connect. To achieve this, I have generated a client certificate using OpenSSL on the server for mutual authorization. The ...