繁体   English   中英

如何让这个代码块在它之后的其他代码之前完成执行?

[英]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)) 该块的执行取决于前一个块。 流程永远不会到达“基本”检查(即第一个 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中使用异步函数,因此您应该“等待”它使用Promise.all创建的所有承诺

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

取自 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}`));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM