Search code examples
vue.jsasync-awaitvuex

Vue, await for Watch


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.


Solution

  • 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
        }
    }