【问题标题】:Promise { <pending> } on node js async function using map使用地图在节点 js 异步函数上承诺 { <pending> }
【发布时间】:2021-11-01 07:57:30
【问题描述】:

尝试将异步函数的数据注入另一个函数并一起返回,但继续接收 [ Promise { }, Promise { } ]。

恢复,我有数组 X ,从一个异步 func 获得,我对其进行迭代,并且为数组 XI 上的每个项目调用另一个异步 func,它使用 map 函数为我提供与数组 X 上的项目相关的数组 Z将数组 Z 与数组 X 上的相关项连接

代码:


 public async execute(): Promise<any> {
    let resultModules;

    this.entityRepository.findAll().then(res => {
      resultModules = res.map(async seg => {
        const modules = await this.segmentModuleRepository.findBySegmentFormatted(
          seg.id,
        );

        console.log('modules: ', modules);

        return {
          ...seg,
          modules,
        };
      });
      console.log('resultModules', resultModules);
    });

    return resultModules;
  }

控制台:

resultModules

应该将所有数组 X 项加上数组 Z 与它们中的每一个相关

【问题讨论】:

标签: javascript node.js asynchronous async-await


【解决方案1】:

您必须使用 Promise.all 等待 map 产生的数组中的承诺

public async execute(): Promise<any> {
  return this.entityRepository.findAll()
    .then(res => Promise.all(res.map(async seg => {
        const modules = await this.segmentModuleRepository.findBySegmentFormatted(seg.id);
        console.log('modules: ', modules);
        return
        {
          ...seg,
          modules,
        };
      }
      ))
    )
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-28
    • 1970-01-01
    • 1970-01-01
    • 2016-01-08
    • 2020-08-13
    • 2019-02-02
    • 1970-01-01
    相关资源
    最近更新 更多