使用自定义键存储数据,调用getData()返回空数组问题排查
嘿,这是异步操作的经典陷阱!你遇到的问题核心是:你的getData()方法没有正确处理异步流程,导致调用它的时候,异步逻辑还没执行完,自然返回空啦。
先拆解下你的代码问题:
getData(): any { this.storage.ready().then(() => { // 这段代码是异步执行的,会在当前方法执行完之后才跑 let data = []; this.storage.forEach((value, key, index) => { if (value.id.startsWith("KEY-")) { data.push(value); } }); // 这里的data只在then回调内部有效,根本没返回给调用方 }); // 方法到这里直接结束了,默认返回undefined或者空,完全没等异步逻辑完成 }
怎么解决?
你需要让getData()返回一个Promise,这样调用方可以等待异步操作完成后拿到结果。给你两种常用的写法:
写法1:用async/await(可读性更高)
async getData(): Promise<any[]> { // 先等storage准备好 await this.storage.ready(); const data: any[] = []; // 遍历存储内容,筛选符合条件的数据 this.storage.forEach((value) => { if (value.id.startsWith("KEY-")) { data.push(value); } }); // 等遍历完成后返回数组 return data; }
写法2:直接返回Promise链(适合习惯链式调用的场景)
getData(): Promise<any[]> { return this.storage.ready().then(() => { const data: any[] = []; this.storage.forEach((value) => { if (value.id.startsWith("KEY-")) { data.push(value); } }); return data; // 把数组作为Promise的最终返回值 }); }
调用的时候也要改!
现在getData()是异步方法了,调用的时候必须用await或者.then()来接收结果:
// 组件里用async/await调用 async loadData() { const matchedData = await this.yourStorageService.getData(); console.log(matchedData); // 这里就能拿到正确的数组啦 } // 或者用链式调用 this.yourStorageService.getData().then(matchedData => { console.log(matchedData); });
额外小建议
- 尽量别用
any类型,定义一个数据接口会让代码更靠谱,比如:
然后把返回类型改成interface StoredItem { id: string; // 加上你存储的其他字段 }Promise<StoredItem[]>。 - 如果你的
storage.forEach是异步方法(比如某些IndexedDB的封装),那还要把遍历逻辑也改成异步的,确保所有数据都筛选完再返回数组。
内容的提问来源于stack exchange,提问作者ghan
相关产品推荐
相关产品推荐

