如何检查数据是否从api返回?

IT技术 javascript css reactjs typescript vue.js
2021-05-22 23:58:00

如何检查我的 api 请求是否从fetchData函数返回任何数据?,我想返回boolean(或其他东西)到我的Index.vue并在加载数据时显示加载器但是当数据加载时我想使用:this.$router.push("admin/dashboard")重定向到另一个页面显示此数据,

我的代码:

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
          })
        })
 }

谢谢你的帮助

3个回答

您可以使用: console.log(response.data)

将数据设置为 response.data 时,请使用 .length 检查大小。如果它 > 0,则将用户路由到仪表板。

以这种方式使用 Js Promises.. 接下来的所有语句将暂停,直到 Promise 解决问题

<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>

参考:https : //www.geeksforgeeks.org/how-to-make-javascript-wait-for-a-api-request-to-return/