如何检查数据是否从api返回? [英] How to check if data is returned from api?
问题描述
如何检查我的 api 请求是否从 fetchData
函数返回任何数据?,我想将 boolean
(或其他)返回到我的 Index.vue
并在加载数据时显示加载器但是当加载数据时我想使用:this.$router.push("admin/dashboard")
重定向到另一个页面显示此数据,
我的代码:
const 动作 = {fetchData({ commit },{ id}) {return axios.get(`someUrl?hd=${id}`).then(响应 => {如果(响应.状态== 200){commit('setData', response.data),}}).抓住(错误 =>{控制台日志(错误);});}}
Index.vue
<vue-spinner/>方法: {...mapActions([fetchData"]),启动获取数据(){新承诺(() => {this.$store.dispatch(fetchData", {id:this.id})})}
感谢您的帮助
以这种方式使用 Js Promises.. 接下来的所有语句将暂停,直到 Promise 解决问题
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script><脚本>函数 makeGetRequest(path) {返回新的承诺(函数(解决,拒绝){axios.get(path).then((响应) =>{var 结果 = response.status;console.log('处理请求');解决(结果);},(错误) =>{拒绝(错误);});});}异步函数 main() {var result = await makeGetRequest('https://jsonplaceholder.typicode.com/users/1');console.log("状态", 结果);console.log('语句 1');console.log('语句 2');}主要的();console.log('开始....');
参考:https://www.geeksforgeeks.org/how-to-make-javascript-wait-for-a-api-request-to-return/
How to check if my api request returns me any data from fetchData
function?, I want to return boolean
(or something else) to my Index.vue
and show loader when data is loading but when data is loaded then i want to use: this.$router.push("admin/dashboard")
to redirect to another page where this data is displayed,
my code:
const actions = {
fetchData({ commit },{ id}) {
return axios.get(`someUrl?hd=${id}`)
.then(response => {
if(response.status == 200) {
commit('setData', response.data),
}
})
.catch(
error => {
console.log(error);
}
);
}
}
Index.vue
<div v-if="isDataLoaded" class="loading-div">
<vue-spinner />
</div>
methods: {
...mapActions(["fetchData"]),
launchFetchData() {
new Promise(() => {
this.$store.dispatch("fetchData", {
id: this.id
})
})
}
thanks for any help
Use Js Promises in this way.. The next all statements will pause until the promise resolve an issue
<body>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
function makeGetRequest(path) {
return new Promise(function (resolve, reject) {
axios.get(path).then(
(response) => {
var result = response.status;
console.log('Processing Request');
resolve(result);
},
(error) => {
reject(error);
}
);
});
}
async function main() {
var result = await makeGetRequest('https://jsonplaceholder.typicode.com/users/1');
console.log("Status ", result);
console.log('Statement 1');
console.log('Statement 2');
}
main();
console.log('starting....');
</script>
</body>
reference: https://www.geeksforgeeks.org/how-to-make-javascript-wait-for-a-api-request-to-return/
这篇关于如何检查数据是否从api返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!