如何使此代码块在它之后的其他代码之前完成执行?

How do I make this code block to finish executing before other codes after it?

在移动到 (if(serviceExists===undefined)) 行之前,我一直在拼命尝试调用“Feature”模型,但无济于事。我认为 async await 是正确的选择,但它也无济于事。

我尝试将第一个 if 块放入 Promise 并将 serviceExists 解析为 Promise 的变量,但这也不起作用。代码流只是等待 Feature.query 获取特征并继续到第二个 if 块,即 (if(serviceExists === undefined))。 而该块的执行取决于前一个块。流程永远不会到达 "base" 检查(即第一个 if 块在第一个外部 if 块中)。如何让它在进一步执行之前等待特征模型的结果?

 let clientFeatures = await ClientFeature.query("clientId")
    .eq(clientMongoId)
    .exec();

  if (clientFeatures.length > 0) {
    var serviceExists;
    clientFeatures.map(async item => {
      let existingFeature = await Feature.queryOne("id")
        .eq(item.featureId)
        .exec();
      let existingFeatureType = existingFeature.type;
      if (
        existingFeatureType === "base" &&
        reSelectedFeatureType === "base"
      ) {
        existingBaseFeatureId = existingFeature.id;
        if (existingBaseFeatureId === reSelectedFeature[0].id) {
          serviceExists = true;
        }
      }
    });
  }

  if (serviceExists === undefined) {
    var clientFeatureGen = await ClientFeature.create({
      id: uuidv1(),
      clientId: clientMongoId,
      featureId: featureMongoId
    });
  }

由于您在 map 中使用异步函数,因此您应该 "wait" 对于它使用 Promise.all

创建的所有承诺

有关详细信息和 CodePen 示例,请参阅此 post

代码取自 CodePen:

const arr = [ { key: 1 }, { key: 2 }, { key: 3 } ]
const results = arr.map(async (obj) => { return obj.key; });
Promise.all(results).then((completed) => document.writeln( `\nResult: ${completed}`));