Home > Back-end >  Wait for fetch function to complete before firing another
Wait for fetch function to complete before firing another

Time:11-18

Currently the console.log(this.detaliiMP) return an empty array. What I want is to wait until the getData() function fetched the data into detaliiMP array and then to log out to the console the array filled with data.

demo

const app = Vue.createApp({
  data() {
    return {
      detaliiMP: []
    }
  },
  methods: {
    getData() {
      fetch("https://random-data-api.com/api/v2/users?size=5")
        .then(res => res.json())
        .then(data => this.detaliiMP = data)
        .catch(err => console.error(err.message))
    },
    showData() {
      this.getData()
      console.log(this.detaliiMP)
    }
  },
})

app.mount('#app')
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>

<div id="app">
  <button @click="getData">Get Data</button>

  <button @click="showData">Console LogOut</button>

  <p v-for="item in detaliiMP">{{ item.first_name }}</p>
</div>

I was trying with async/await but clearly I did something wrong, because is not working.

CodePudding user response:

It's async/await matter.

const app = Vue.createApp({
  data() {
    return {
      detaliiMP: []
    }
  },
  methods: {
    async getData() {
      await fetch("https://random-data-api.com/api/v2/users?size=5")
        .then(res => res.json())
        .then(data => this.detaliiMP = data)
        .catch(err => console.error(err.message))
    },
    async showData() {
      await this.getData()
      console.log(this.detaliiMP)
    }
  },
})

app.mount('#app')
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>

<div id="app">
  <button @click="getData">Get Data</button>

  <button @click="showData">Console LogOut</button>

  <p v-for="item in detaliiMP">{{ item.first_name }}</p>
</div>

  • Related