Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue, await for Watch

Tags:

vue.js

vuex

i have similar architecture in my app.

computed(){ 
   someStoreValue = this.$store.someStoreValue; 
}
watch() { 
   someStoreValue() = async function () { 
    //do some async action 
   
   }
}, 
methods: { 
  someAction() {        
     this.$store.someStoreValue = 'NEW VALUE'     
     //await for "watch" 

     //do stuff

  }
}

I need to "someAction" await for "someStoreValue" watcher ends. I need this kind of architecture someStoreValue can be changed in many places.

like image 583
user88831 Avatar asked Jul 31 '20 08:07

user88831


2 Answers

Sure, you can't make your watchers async, which is pretty senseless since the data you are after has already arrived.

someStoreValue(newValue, oldValue) { 
    // But you can still call other async functions. 
    // Async functions are just functions that returns a promise. Thus:
    doSomeAsyncAction().then(this.someAction)
}

Still, why not just do your async stuff in someAction instead?

watch:{ 
    someStoreValue(newValue, oldValue) { 
        this.someAction()
    }
},
methods:{
    async someAction(){
        await doSomeAsyncStuff() // What prevents you from doing this?
        //do stuff
    }
}
like image 195
ippi Avatar answered Oct 19 '22 23:10

ippi


You can use a flag and wait for it.


data() {
   return {
      flag: false
   }
},
watch() { 
   someStoreValue() = async function () { 
    //do some async action 
  
     flag = true;  
   }
}, 
methods: { 
  async someAction() {        
     this.$store.someStoreValue = 'NEW VALUE'     
     await new Promise((resolve) => {
       if (this.flag) {
         resolve();
       } else {
         const unwatch = this.$watch('flag', (newVal) => {
           if (newVal) {
             unwatch();
             resolve();
           }
         });
       }
      });

     //do stuff

  }
}

Maybe in this case the @ippi solution is better, but you can use this approach in other cases.

like image 33
Dicren Avatar answered Oct 20 '22 00:10

Dicren