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

What is the process for deleting an animation using JavaScript, and how can the background color be altered?

Two issues are currently troubling me. First off, I am facing a challenge with an animation feature that I need to modify within the "popup" class for a gallery section on a website. Currently, when users load the page, a square image and background start ...

I am struggling to display an array of objects retrieved from the server in the UI using AngularJS

I am receiving an array of objects as a JSON from the server. When I try to access my service URI from HTML, I encounter the following array in my console: "angular.js:13920 Error: [$resource:badcfg] http://errors.angularjs.org/1.5.8/$resource/badcfg?p0= ...

What is the process for sending text messages in a local dialect using node.js?

Having an issue with sending bulk SMS using the textlocal.in API. Whenever I try to type a message in a regional language, it displays an error: {"errors":[{"code":204,"message":"Invalid message content"}],"status":"failure"} Is there a workaround for se ...

Model for handling Node/Express requests

I always saw Node.js/Express.js route handlers as akin to client-side EventListeners such as onClick, onHover, and so on. For example: document .getElementById('btn') .addEventListener('click', function() { setTimeout(functi ...

Stay connected with AJAX's latest updates on Twitter with just 13 bytes

Twitter sends a POST request of only 13 bytes when someone follows an account. This small amount of information helps to reduce latency and server load, providing advantages for web developers. However, removing unnecessary cookies and extra information f ...

Revise a catalog when an object initiates its own removal

When rendering a card in a parent component for each user post, all data is passed down through props. Although the delete axios call works fine, I find myself having to manually refresh the page for updates to be displayed. Is there a way to have the UI ...

What is the process for retrieving the value of `submit.preloader_id = "div#some-id";` within the `beforesend` function of an ajax call?

In my JavaScript code, I have the following written: var formSubmit = { preloaderId: "", send:function (formId) { var url = $(formId).attr("action"); $.ajax({ type: "POST", url: url, data: $(formId).serialize(), dataTy ...

Cover the entire screen with numerous DIV elements

Situation: I am currently tackling a web design project that involves filling the entire screen with 60px x 60px DIVs. These DIVs act as tiles on a virtual wall, each changing color randomly when hovered over. Issue: The challenge arises when the monitor ...

navigating to the start of a hyperlink

I'm having issues with scrolling to anchors and encountering 3 specific problems: If I hover over two panels and click a link to one of them, nothing happens. When I'm on section D and click on section C, it scrolls to the end of section C. ...

Unable to retrieve Angular Service variable from Controller

I am facing an issue with my Angular Service. I have set up two controllers and one service. The first controller fetches data through an AJAX call and stores it in the service. Then, the second controller tries to access this data from the service. While ...

Unexpected element layout issues

Attempting to create a basic website that utilizes the flickr api, retrieves photos and details, and displays them using bootstrap. However, there seems to be an issue that I am unsure how to resolve. Currently, my code is functioning like so: https://i.s ...

Indeed, verifying parent.parent access

Currently, I am utilizing the yup module to validate my form. My objective is to access the parent in order to test the value. Below is my schema: enabled: yup.boolean(), contactDetail: yup.object().shape({ phoneNumber1: yup.string().nullable(), pho ...

Using Vue to handle Promise resolution - incorporating Laravel Gate logic into Vue

Trying to incorporate Laravel's authorization and policy into Vue has been a challenge for me. I'm working on creating a mixin that sends a GET request to a backend controller. The issue I've encountered is that the v-if directive is receiv ...

Expand the scope of the javascript in your web application to cater

I am in the process of creating a web application that utilizes its own API to display content, and it is done through JavaScript using AJAX. In the past, when working with server-side processing (PHP), I used gettext for translation. However, I am now ...

Obtain the name of a node using its identification number in D3JS

I am currently working on implementing a generalized tooltip feature. This tooltip will display the name and other relevant data of the active node. For example, if node 3 is currently active, the tooltip will show the name and distance (not link distance) ...

Remove chosen tags from the options list in Material UI Autocomplete Multiple

When utilizing the Material UI Autocomplete for multiple values, the selected input is shown in the options list with a blue background color. Is there a way to configure the autocomplete to exclude already selected values from appearing in the options li ...

How to modify a value in a document within a MongoDB collection

I'm having an issue with updating the 'panel' field in both the cards collection and projects collection. Here is my code snippet: const project = await Project.findOne({"code":currentUser.groupcode}); // this works const ...

Switching between languages dynamically with Angular JS using $translateProvider and JSON files

I currently have a collection consisting of 6 different JSON files. en.json es.json fr.json it.json ja.json zh.json An illustration of the data present in each file is as follows (in this instance, considering en.json): { "SomeText": "Test in Englis ...

socket.io / settings when establishing a connection

I'm facing an issue in my node.js / Express.js app where I need to pass parameters with the socket.io connection (saw a solution in another post). On the client side, here is a snippet of my code: edit var socket = io.connect('/image/change&ap ...

Ways to ascertain if a view has completed rendering in JavaScript

I am currently building my application using the awesome backbone.js framework. Within my code, I have this layoutView that handles rendering the overall layout and also includes a smaller profile section. The dilemma I'm facing is with the timing o ...