You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Capacitor Storage时序问题:同步返回L.Map实例时异步取值报错如何解决

解决方案

核心原因是Storage.get为异步API,同步声明的函数无法等待异步操作完成再返回结果,这里提供两种可行方案:

方案1:异步改造函数(推荐)

将函数改为异步返回Promise<L.Map>,等待Storage取值完成后再初始化地图,保证坐标取值正确:

// 修改函数返回类型为Promise<L.Map>
async generateMap(id: string, zoom: number): Promise<L.Map> {
  let current_position = {
    latitude: 52.3702157,
    longitude: 4.8951679
  }
  // 等待异步取值完成
  const result = await Storage.get({ key: 'current_position' })
  if (result.value != null) {
    current_position = JSON.parse(result.value);
  }
  const map = L.map(id,
    {
      zoom: zoom,
      center: latLng({ lat: current_position.latitude, lng: current_position.longitude }),
    });
  return map;
}

调用时需要配合await或者.then()使用:

// 调用示例1:用then处理
generateMap('map-container', 12).then(map => {
  // 后续地图操作逻辑写在这里
})
// 调用示例2:在async函数内用await
const map = await generateMap('map-container', 12)

方案2:同步返回地图,异步更新中心

如果不想修改原函数的返回类型和调用逻辑,可以先用默认坐标初始化地图,等Storage取值完成后动态修改地图中心:

generateMap(id: string, zoom: number): L.Map {
  const default_position = {
    latitude: 52.3702157,
    longitude: 4.8951679
  }
  // 先用默认坐标初始化地图
  const map = L.map(id,
    {
      zoom: zoom,
      center: latLng({ lat: default_position.latitude, lng: default_position.longitude }),
    });
  // 异步获取存储的坐标后更新地图中心
  Storage.get({ key: 'current_position' }).then((result) => {
    if (result.value != null) {
      const current_position = JSON.parse(result.value);
      map.panTo(latLng(current_position.latitude, current_position.longitude))
    }
  });
  return map;
}

该方案下地图会先显示默认坐标位置,拿到存储坐标后平滑跳转至目标位置,不会影响函数返回值类型。

内容的提问来源于stack exchange,提问作者S_NoBEl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 16:54:04