簡體   English   中英

從異步/等待返回數據 axios 總是返回 promise

[英]Return a data from async/await axios always return a promise

我的目標是在方法中將數組中的 id 傳遞給 axios 並返回結果

<template>
    <div v-for="person in data">
          <h2>{{ person.name }}</h2>
          // Im calling a method, I want to return a data
          <h3>{{ getPersonReviews(person._id) }}</h3>
    </div>
</template>

<script>
export default {
  data() {
     return {
         personData: [{ _id: 3, name: "Donald Trump"}, {_id: 2, name: "Jack"}]

     }

   methods: {
       async getPersonReviews(id) {
           let response = await this.axios.get('http://localhost:3000/api/person-review');
           console.log(response.length) ---> Will return the number eg: 0,2,3
           return response.length ---> Will return [Object promise]

       }

    }

  }

}
</script>

不知何故,如果我console.log()它將返回正確的數據,但是當我返回數據時,它將返回[Object promise] 如果不可能,那么我將使用另一種解決方案。

JavaScript 中的async function 始終返回 Promise。

獲得解析值的唯一方法是在 function 內部設置一個存在於 promise 之外的值:

<template>
    <div v-for="person in data">
          <h2>{{ person.name }}</h2>
          // Im calling a method, I want to return a data
          <h3>{{ displayValue[person._id] }}</h3>
    </div>
</template>

<script>
export default {
  data() {
     return {
         personData: [{ _id: 3, name: "Donald Trump"}, {_id: 2, name: "Jack"}],
         displayValue: {}
     }
  },
  // trigger data fetch on component load
  mounted() {
      this.personData.map(p => p._id).forEach(this.getPersonReviews);
  },
  // trigger data fetch whenever personData or any of its values change:
  watch: {
      personData: {
          deep: true, // without this, this watcher will only be triggered by 'this.personData = value' statements
          handler() {
              this.personData.map(p => p._id).forEach(this.getPersonReviews);
          }
      }
  },
   methods: {
       async getPersonReviews(id) {
           let response = await this.axios.get('http://localhost:3000/api/person-review');
           console.log(response.length) ---> Will return the number eg: 0,2,3
           this.displayValue[id] = response.length;

       }

    }

  }

}
</script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM