This is not a duplicate of How do I return the response from an asynchronous call? I know that JS is asynchronous, what I am looking for is the Vue way to address the problem.
I have a Vue.js page where some data need to be updated based on the response of an API. The code below does not work because return r.status
returns from the fetch
and not from getName
.
new Vue({
el: "#app",
data: {
elements: ["400", "401"],
newelements: []
},
methods: {
// take each elementfrom elemets and update it with the result of an asynchronous function
updateData() {
this.elements.forEach(x => {
this.newelements.push(this.getName(x) + 1000)
console.log(`processing ${x}`)
})
},
// the asynchronous function
getName(x) {
fetch(`https://postman-echo.com/status/${x}`)
.then(r => r.json())
.then(r => {
console.log(`received status ${r.status}`)
// here I return from fetch, but I would like r.status to be returned by getName
return r.status
})
},
},
mounted() {
this.updateData()
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div v-for="el in elements">{{el}}</div>
<div v-for="el in newelements">{{el}}</div>
</div>
Which is the correct approach to update newelements?