【问题标题】:How to check if data is returned from api?如何检查是否从api返回数据?
【发布时间】:2021-04-16 18:02:17
【问题描述】:

如何检查我的 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
          })
        })
 }

感谢您的帮助

【问题讨论】:

    标签: javascript css reactjs typescript vue.js


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

        以这种方式使用 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/

        【讨论】:

          猜你喜欢
          • 2018-07-26
          • 1970-01-01
          • 1970-01-01
          • 2019-06-20
          • 1970-01-01
          • 2010-09-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多