While reviewing the code of a frontend project developed in Vue3, I came across a unique construction that I have not encountered before. This has led to some confusion as I try to grasp how it operates. The concept involves assigning the result of an asynchronous call (such as fetching JSON data using fetch
) to a reactive value.
The method I am accustomed to is demonstrated in the following code snippet (Vue Playground). Here, the use of setTimeout
simulates the asynchronous operation, returning a Promise that is subsequently handled through a then()
function to set the reactive variable msg
.
<script setup>
import { ref } from 'vue'
const msg = ref('one')
const asyncCall = () => new Promise((resolve, reject) => {
setTimeout(() => {
resolve("two");
}, 2000);
})
asyncCall().then(r => msg.value = r)
</script>
<template>
<h1>{{ msg }}</h1>
</template>
On the other hand, the unconventional approach I encountered (Vue Playground) creates a local reactive variable within a function, executes the asynchronous call, and upon resolution, assigns the value to that local ref variable. The function then returns the ref value (visual sequence, actual execution differs).
<script setup>
import { ref } from 'vue'
const msg = ref('x')
const asyncCall = () => {
const result = ref('one')
setTimeout(() => {
result.value = 'two'
}, 2000)
return result
}
msg.value = asyncCall()
</script>
<template>
<h1>{{ msg }}</h1>
</template>
Although this alternative approach works, I find myself questioning:
- ... the persistence of the local variable
result
beyond the scope ofasyncCall
, with its default value of
occurs.one</code even before the callback in <code>setTimeout()
- ... the ability to return
result
(a pointer) while assigning it tomsg.value
(a string), and witnessing successful functionality. ... the presence of quotation marks around the displayed values ("one"
and"two"
), which has been addressed in a separate discussion here.
My question: Is this second approach valid? Is it recommended? Although it simplifies the code by consolidating the asynchronous process within the function, it deviates from traditional practices that I am familiar with.