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.
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
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With