-2

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?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
WoJ
  • 27,165
  • 48
  • 180
  • 345
  • @jonrsharpe: no, this was the first suggestion when writing the question. I am not trying to understand that JS is asynchronous but the right way, in Vue, to manage these situations. – WoJ Jul 10 '20 at 18:55
  • 2
    it's the same question though, and the answers to it still apply. Your issue is nothing to do with Vue. (I don't actually know Vue very well.) – Robin Zigmond Jul 10 '20 at 19:02
  • 1
    Well getName *can't* return the value, only a *promise* of it; I think you'd still get value reading the canonical, fixing your basic mistakes and focusing on any Vue-specific problem that remains. – jonrsharpe Jul 10 '20 at 19:03

1 Answers1

0

make a property function in the object and then return it something like

getName: (x) =>{
     return 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
        })
    },
Sven.hig
  • 4,449
  • 2
  • 8
  • 18