Search code examples
javascriptasync-awaitmap-function

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


I have been desperately trying to make a call to the "Feature" model before moving to (if(serviceExists===undefined)) line as shown below but to no avail. I thought async await was the way to go but it doesn't help either.

I have tried putting the first if block in a Promise and resolving the serviceExists to a variable for Promise but that didn't work either. The code flow simply waits for the Feature.query to fetch the features and goes on to the 2nd if block i.e (if(serviceExists === undefined)). And the execution of that block depends on the previous one. The flow never reaches the "base" check (i.e. 1st if block in the 1st outside if block). How do I make it such that it waits for the result from Feature model before further execution?

 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
    });
  }

Solution

  • Since you are using asynchronous function in map you should "wait" for all promises that it creates using Promise.all

    See this post for details and CodePen example.

    Code taken from the 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}`));