美文网首页Vue生态圈Vue.js
async/await 实现axios同步

async/await 实现axios同步

作者: 知足常乐晨 | 来源:发表于2019-08-01 09:56 被阅读3次

项目中经常会用到axios获取json文件中数据,但是总会因为异步问题出现数据还没有返回程序已经进行向下执行,导致报错,这种异步造成的问题最直接的解决方法就是把axiso的异步方法改成同步,使用ES7新出的特性的新特性,async/await 实现axios同步
MockData.js

    async createRealWorker() {
        let gridData = null;
        let result = await axios.get(jsonUrl + '/police.json').then(res => {
            var features = [];
            let workerList = [];
            let list = res.data;
            // for (var i = 0; i < list.length; i++) {
            let i=0;
            while(i<list.length){
                let lon = list[i].lon;
                let lat = list[i].lat;
                // let props = list[i];
                let tel = list[i].telephone.toString().substring(0,7);
                let props = {
                    'id': list[i].id,
                    'code': list[i].code+""
                };
                workerList.push(props);

                let point = transform([lon, lat], "EPSG:4326", "EPSG:3857")
                if(list[i].status){
                    features.push({
                        "type": "Feature",
                        "properties": props,
                        "geometry": {
                            "type": "Point",
                            "coordinates": point
                        }
                    });
                }
                i++;
            }
            store.commit('SET_WORKER_LIST', workerList);
            gridData = {
                "type": "FeatureCollection",
                "features": features
            }
            // return gridData;
        })
        result = gridData;
        return result;
    },

调用时注意任何async函数都会默认返回promise

let geojsonObject = MockData.createRealWorker();
geojsonObject.then(res => {
      ...
})

相关文章

网友评论

    本文标题:async/await 实现axios同步

    本文链接:https://www.haomeiwen.com/subject/msgfdctx.html