watcher performs sycnhronous or asynchronous

 In Vue.js, watchers can be synchronous or asynchronous depending on how they are implemented.

By default, watchers are synchronous, which means that they are executed immediately when a watched property changes, before any other code is executed. This can be useful for performing simple operations that don't require any asynchronous or time-consuming operations.

However, there may be cases where you need to perform asynchronous operations inside a watcher, such as making an API call or performing a long-running task. In these cases, you can make the watcher asynchronous by using the async keyword and await keyword inside the watcher function.

Here's an example of an asynchronous watcher:

javascript
watch: { myData: async function (newVal, oldVal) { 
try { // Perform an asynchronous operation, such as making an API call 
const response = await fetch('/my/api', { method: 'POST', body: JSON.stringify(newVal) }); // Handle the response 
const data = await response.json(); this.result = data.result
 } 
catch (error) { 
console.error(error); 
 } 
 } }

In this example, the myData watcher is declared as an asynchronous function using the async keyword. Inside the function, an asynchronous operation is performed using the await keyword, which waits for the operation to complete before moving on to the next line of code.

Note that if you use an asynchronous watcher, it may cause delays in the rendering of the view, since the watcher is not executed immediately and may take some time to complete its oper

No comments:

Post a Comment

Event listening in react

 How we can listen to som eevents some envents fire like click or automatically user enters into input button , that is event on word type i...