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

async/await环境下向数组push元素无效问题求助

问题:async/await环境下向数组push元素后返回空数组

你遇到的核心问题是forEach不支持异步等待,加上异步操作还没执行完就返回了数组,导致最终拿到空数组。另外代码里还有个小问题:JSON.parse是同步方法,不需要加await。

问题分析

  1. forEach的异步陷阱:dir.forEach(async (file) => { ... })里的async回调会被当作独立的Promise,但forEach不会等待这些Promise完成。你的collection方法在遍历开始后直接返回this.$collection,这时候所有的readDoc异步操作还没执行,数组自然是空的。
  2. 多余的await:readDoc里的await JSON.parse(buffer)完全没必要,JSON.parse是同步解析,加await只会把它包装成一个立即resolve的Promise,没有实际作用。

修正方案

用map生成所有读取文档的Promise数组,再通过Promise.all等待所有异步操作完成,之后再更新数组或者直接返回结果:

class Store {
  $collection: Document[] = [];

  collection = async (): Promise<Document[]> => {
    const dir = await readdir("docs");
    // 用map生成Promise数组,再用Promise.all等待全部完成
    const documents = await Promise.all(dir.map(file => this.readDoc(file)));
    // 更新$collection数组
    this.$collection.push(...documents);
    // 返回结果
    return this.$collection;
  };

  readDoc = async (uuid: string): Promise<Document> => {
    const buffer = await readFile(`docs/${uuid}`, "utf-8");
    // JSON.parse是同步方法,去掉await
    const data = JSON.parse(buffer);
    return { uuid, data };
  };
}

const store = new Store();
console.log(await store.collection()); // 现在会返回预期的文档数组

关键改动说明

  • 用dir.map(file => this.readDoc(file))把每个文件转换成读取文档的Promise,这样能收集所有异步任务。
  • Promise.all(documentsPromises)会等待所有Promise都resolve后,返回一个包含所有结果的数组。
  • 用扩展运算符...把所有文档一次性push到$collection,比循环push更高效。
  • 去掉readDoc里多余的await,避免不必要的Promise包装。

这样修改后,collection方法会等待所有文档读取完成后再返回数组,就能得到预期的结果了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 00:12:03