方法中的等待 axios 请求未及时完成



在我的组件中,我有一些相互依赖的 API 调用:

async mounted() {
    // Call 1
    await axios.get('/api/users/' + userId).then(response => {
      this.dataNeeded = response.data
    })
    // Call 2
    axios.get('/api/somethingelse').then(response => {
      this.dataNeeded[response.data[0]] // <-- need to fetch this.dataNeeded 
    })
 }

这行得通!

然而。。。我想将函数(调用 1(移动到一个方法以重复调用它并使用:

methods: {
    axiosCall1: async function() {
    axios.get('/api/users/' + userId).then(response => {
      this.dataNeeded = response.data
    })
}
await this.axiosCall1();
// axiosCall2 should now be able to use this.dataNeeded. 
// However this.dataNeeded is now: {__ob__: Observer}
// And not an object {} with data
this.axiosCall2();

任何人都可以1发现可能出错的地方吗?

await错误的地方。您应该await异步操作(在我们的例子中axios.get()(

await 阻止异步函数中的代码执行

试试这个

methods: {
  axiosCall1: async function() {
    await axios.get('/api/users/' + userId).then(response => {
      this.dataNeeded = response.data
    })
  },
  ...
}

然后

this.axiosCall1();
// axiosCall2 should now be able to use this.dataNeeded. 
// And this.dataNeeded is now: an object {} with data
this.axiosCall2();

最新更新