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

TypeScript中嵌套map内异步方法如何无需then获取结果

不用then获取ZoneAwarePromise结果的解决方案

先修正方法代码

你的method函数里多余了await,直接返回firstValueFrom的结果即可:

private method(u: User, s: string): Promise<string> {
    return firstValueFrom(this.translate.get(u.abcd(s)));
}

用async/await + Promise.all解析嵌套Promise

因为你是嵌套map,得到的是Promise<string>[][]结构,需要两层Promise.all来解析所有异步任务,同时用await获取最终结果:

async getFinalResults() {
  // 外层Promise.all解析每个用户对应的Promise数组
  const finalResults = await Promise.all(
    a.map(user => {
      // 内层Promise.all解析当前用户对应的所有字符串翻译Promise
      return Promise.all(b.map(str => this.method(user, str)));
    })
  );
  console.log(finalResults); // 这里就是解析完成的string[][]
}

在async上下文调用

必须在async函数中使用await,比如Angular组件的生命周期钩子:

async ngOnInit() {
  await this.getFinalResults();
}

这样就能直接拿到最终结果,全程不需要使用then。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 21:41:04