If we take the following Vuejs component:
<script setup>
import { ref, watch } from 'vue'
const question = ref('')
const answer = ref('')
watch(question, async (newQuestion) => {
if (newQuestion.includes('?')) answer.value = 'that is a question'
else setTimeout(() => {answer.value = 'that is not a question'}, 1000)
})
</script>
<template>
<input v-model="question" />
<p>{{ answer }}</p>
</template>
This component is supposed to tell you if the text submitted has a question mark or not. Obviously in a real application you wouldn’t have the setTimeout function after the else
statement, however I put it there for the sake of the example (imagine in a real scenario the else case has some logic that takes longer than the if statement). Also imagine there was some reason for the watch function to be asynchronous, for example instead of setting the answer ref you do an api call. The problem that occurs now is that if you remove the question mark and then add it quick enough, the watch function called when the question mark wasn’t there is finished after and you get the following output:
I was wondering if there was any way to make the watch function be executed sequentially, so that the latest call is that last update of the question variable.
I looked through the Vuejs docs but I couldn’t find anything about forcing the watch function to be called asynchronously. Thank you