VueJs - 来自 API 调用的数据第一次未到达第 2 API 调用
VueJs - Data from API call doesn't reach 2nd API call first time
我有 2 个 API 调用,第二个调用 运行s 间隔 x 秒并且取决于来自第一个调用的数据。现在我想第一次 运行 这个时间间隔,但我无法让它正常工作。
做了一些搜索,显然有多种解决方案,我试过了:
- 运行区间前一次函数
- 函数中的 setTimeout
这些选项应该有效,但由于某些原因,我第二次调用所需的第一次调用的数据没有出现。
created() {
this.fetchId();
this.fetchItems(); //this doesn't get the id set in fetchId()
setInterval(
function() {
this.fetchItems();
}.bind(this),
50000
);
},
methods: {
fetchId() {
axios
.get("two/id")
.then(response => {
this.id = response.data.id;
})
.catch(error => {
console.log(error);
});
},
fetchItems() {
axios
.get("one/api/public-stash-tabs?id=" + this.id)
.then(response => {
//do something
})
.catch(error => {
console.log(error);
});
}
}
所以这样,我在 fetchItems().axios.get(..) 中需要的 this.id 在间隔之前的第一次 运行 中不起作用。当我删除此函数调用并等待前 x 秒时,一切正常。
发生这种情况是因为axios.get(...)
是一个异步调用,这意味着fetchId()
方法将在后台运行,而fetchItems()
方法在[=12]之后立即被调用=] 甚至在设置 this.id
之前,所以在 fetchItems()
方法中 this.id
总是未定义的。您可以使用 async/await
解决此问题,例如:
created() {
this.init(); // use a wrapper method here
},
methods: {
async init() { // using async method here
await this.fetchId(); // wait for fetchId call to finish
this.fetchItems();
},
fetchId() {
return axios // return the promise here, so that we can await on it
.get("two/id")
.then(response => {
this.id = response.data.id;
})
.catch(error => console.log(error));
},
fetchItems() {
axios
.get("one/api/public-stash-tabs?id=" + this.id)
.then(response => {
//do something
})
.catch(error => console.log(error));
}
}
我有 2 个 API 调用,第二个调用 运行s 间隔 x 秒并且取决于来自第一个调用的数据。现在我想第一次 运行 这个时间间隔,但我无法让它正常工作。
做了一些搜索,显然有多种解决方案,我试过了:
- 运行区间前一次函数
- 函数中的 setTimeout
这些选项应该有效,但由于某些原因,我第二次调用所需的第一次调用的数据没有出现。
created() {
this.fetchId();
this.fetchItems(); //this doesn't get the id set in fetchId()
setInterval(
function() {
this.fetchItems();
}.bind(this),
50000
);
},
methods: {
fetchId() {
axios
.get("two/id")
.then(response => {
this.id = response.data.id;
})
.catch(error => {
console.log(error);
});
},
fetchItems() {
axios
.get("one/api/public-stash-tabs?id=" + this.id)
.then(response => {
//do something
})
.catch(error => {
console.log(error);
});
}
}
所以这样,我在 fetchItems().axios.get(..) 中需要的 this.id 在间隔之前的第一次 运行 中不起作用。当我删除此函数调用并等待前 x 秒时,一切正常。
发生这种情况是因为axios.get(...)
是一个异步调用,这意味着fetchId()
方法将在后台运行,而fetchItems()
方法在[=12]之后立即被调用=] 甚至在设置 this.id
之前,所以在 fetchItems()
方法中 this.id
总是未定义的。您可以使用 async/await
解决此问题,例如:
created() {
this.init(); // use a wrapper method here
},
methods: {
async init() { // using async method here
await this.fetchId(); // wait for fetchId call to finish
this.fetchItems();
},
fetchId() {
return axios // return the promise here, so that we can await on it
.get("two/id")
.then(response => {
this.id = response.data.id;
})
.catch(error => console.log(error));
},
fetchItems() {
axios
.get("one/api/public-stash-tabs?id=" + this.id)
.then(response => {
//do something
})
.catch(error => console.log(error));
}
}