React---在React项目中使用Promise封装获取城市定位函数

在React项目中使用Promise封装获取城市定位函数

import axios from "axios";
// 1.导出获取定位城市的函数getCurrentCity
export const getCurrentCity = () => {
  // 2.判断localStorage中是否有定位城市
  const LocalCity = JSON.parse(localStorage.getItem('hkzf_city'))
  if (!LocalCity) {
    // 3.如果没有,就使用首页中获取定位城市的代码来获取,并且存储到本地存储中,然后返回该城市数据
    return new Promise((reslove, reject) => {
      // 根据定位获取城市名称
      var myCity = new window.BMapGL.LocalCity();
      myCity.get(async (result) => {
        try {
          const { data: res } = await axios.get(`http://localhost:8081/area/info?name=${result.name}`)
          // console.log(res.body);
          localStorage.setItem('hkzf_city', JSON.stringify(res.body))
          reslove(res.body)
        } catch (error) {
          reject(error)
        }
      });
    })
  }

  // 4.如果有,直接返回本地存储中的城市数据
  return Promise.resolve(LocalCity)
}

猜你喜欢

转载自blog.csdn.net/h18377528386/article/details/124258870