good-storage无法缓存的问题

学习中遇到一个问题,想请教一下,我在用good-storage插件,想把我获取到的图片放到本地缓存中,但是goodStorage.set('imgList',this.imgList),这个this.imgList是个对象,但是用这个却没办法把他存到缓存中

import goodStorage from 'good-storage'
export class LmgUtil{
    static imgList:Record<string,string> = {}
    static storageLmgList(){
        this.imgList = goodStorage.get('imgList') || {}
        if(this.isEmpty()){
            this.loadAllLmg()
            console.log(this.imgList)   //这里也可以打印出这个对象
            goodStorage.set('imgList',this.imgList) //这里就无法把他存到缓存中,改用其他数据就行
        }
    }
    static isEmpty(){
        return !Object.getOwnPropertyNames(this.imgList).length
    }

   //这里是把图片加载到内存
    static loadAllLmg(){
      const imgMap =  import.meta.glob(
            '../assets/img/**/*.png'  
        )
        let absolutePath:string = ''
        let imgName:string = '' 
        for(let relatviepath in imgMap){
             imgMap[relatviepath]().then(  
                (res:any)=>{
                   absolutePath = res.default
                   imgName = absolutePath.substring(absolutePath.lastIndexOf('/')+1)
                   this.imgList[imgName] = absolutePath  
                }
             )
        }
        return this.imgList
    }
}


你之前的代码中出现了异步问题,goodStorage.set() 方法被调用的时机可能在 this.loadAllLmg() 方法执行之前,因为 this.loadAllLmg() 方法中使用了异步操作(Promise)。这就导致了 goodStorage.set() 方法存储的是空的 this.imgList。

要解决这个问题,你可以将 goodStorage.set() 方法的调用放在所有图片加载完成后执行,即在 this.loadAllLmg() 方法的 Promise 全部完成后再执行。这样保证了 this.imgList 已经被正确填充后再存储。

以下是修改后的代码:

import goodStorage from 'good-storage';

export class LmgUtil {
  static imgList: Record<string, string> = {};

  static async storageLmgList() {
    this.imgList = goodStorage.get('imgList') || {};
    if (this.isEmpty()) {
      await this.loadAllLmg(); // 使用await等待loadAllLmg方法执行完成
      console.log(this.imgList);
      goodStorage.set('imgList', this.imgList);
    }
  }

  static isEmpty() {
    return !Object.getOwnPropertyNames(this.imgList).length;
  }

  // 这里是把图片加载到内存
  static async loadAllLmg() {
    const imgMap = import.meta.glob('../assets/img/**/*.png');
    let absolutePath: string = '';
    let imgName: string = '';
    for (let relatviepath in imgMap) {
      const res = await imgMap[relatviepath](); // 使用await等待图片加载完成
      absolutePath = res.default;
      imgName = absolutePath.substring(absolutePath.lastIndexOf('/') + 1);
      this.imgList[imgName] = absolutePath;
    }
    return this.imgList;
  }
}
通过使用 await 等待异步操作完成,你可以确保 this.imgList 已经被正确填充后再执行 goodStorage.set() 方法,这样就可以正确地将图片数据存储到缓存中了。