第二层嵌套承诺

时间:2021-06-03 20:47:20

标签: typescript mongodb asynchronous promise

我有一个高级 Mongo 查询。

我尝试计算多个字段的不同值的地方。

首先,我必须迭代三个值,它们是我的 Mongoose 模式中的条目,然后我必须计算每个字段的每个不同值,并将它们作为字符串返回。


const mappedStuff = this.featureFields.map(async field => {
      return new Promise(async (resolve, reject) => {
        const distinctValues = await this.gameModel.distinct(field);
        return distinctValues.map(async entry => {
          console.log(
            `${field}, ${entry},  ${await this.gameModel.count({
              [field]: entry,
            })}`,
          ); //Logs out correct value 
          resolve(
            `${field}, ${entry},  ${await this.gameModel.count({
              [field]: entry,
            })}` as string, //resolves instantly and does not return the correct value
          );
        });
      });
    });
    console.log(Promise.all(mappedStuff));
    return Promise.all(mappedStuff);

console.log 工作正常,我只想返回该值,我尝试将它推送到外部的列表,但不起作用,因为我在字符串中有一个 await

因此,我尝试将整个事情包装在一个 Promise 中,但这也不能解决问题。有没有人有解决办法

1 个答案:

答案 0 :(得分:4)

您使用 Promise.all() 包装外部数组做了正确的事情,但是您忘记对内部数组做同样的事情,其中​​有 <?xml version='1.0' ?> <InboundDataXml> <CustomAttributes> <CustomAttribute> <AttributeName>Trace Id</AttributeName> <AttributeValue>IEHPTraceID_123456</AttributeValue> </CustomAttribute> </CustomAttributes> </InboundDataXml> 。此外,直接在外部映射中的 Promise 似乎是多余的。

distinctValues.map(//...