How to return an observer from a global function in Vue 2
P粉682987577
2023-09-05 22:03:02
<p>Hello, I have a question: In main.js, I have a global function <code>getSites</code> that retrieves the list of sites from the API. </p><p>
This function works using async/await and returns site data asynchronously. </p><p>
I also have a global variable called <code>lockSitesLoading</code> which I set to true when I start getting data from the API, I need this variable to prevent the client from making new requests to the server. </p><p>
In the first function <code>getSites</code>, I need to check this variable <code>lockSitesLoading</code> and if it is true, start monitoring it until it changes to false. At this point, I want to call <code>getSites</code> recursively. </p><p>
The problem starts now because when I start watching the variable, the function does not wait for the variable to become false, but returns <code>undefined</code>. </p><p>
Here is my code: </p>
<p>Component.vue:</p>
<pre class="brush:php;toolbar:false;">async mounted() {
let vm = this;
const sites = await vm.getSites();
vm.sites = sites.data
},</pre>
<p>main.js:</p>
<pre class="brush:php;toolbar:false;">async getSites() {
let vm = this;
if (vm.$store.state.lockSitesLoading) {
vm.$watch('$store.state.lockSitesLoading', () => vm.getSites());
} else {
return vm._getSitesOnline();
//This is the function that actually gets the data from the server
}</pre>
<p>I tried solving it this way but it doesn't work. Any ideas? </p>
I don’t know if you set
lockSitesLoading = true
, and I don’t know where you set it.This is a working example.
Basically requires a promise to wait for:
Please note that if
lockSitesLoading
blocks execution for some reason, this will cause a memory leak.There may be a cleaner way to achieve this using the composition API and VueUse compositions.