title: How to push to a list in an Asynchronous Task and return the list only after the async task is finished?
body: <p>I am having problem returning a list.  First, I add element to the list from querying the database and once the DB querying is finished then only I return the list.  But, I realized that querying is happening asynchronously and this code is returning before it has finished querying all the datas and adding it to the list.</p>
  
  <p>I know in other languages, we could've used Mutex or Semaphore to solve this issue of race conditions but How can we deal with this in Javascript?  </p>
  
  <pre><code>    let all_recipe= []
          for(let i =0; i&lt;result.chefs.email.length; ++i)
          {
  
              chefSchema['chef'].findOne({"email":result.chefs.email[i]},"recipe")
              .then(recipes=&gt;{
                  if(recipes!=null)
                  {
  
                      if(recipes.recipe.length!=0)
                      {
                          all_recipe.push(recipes.recipe);
                      }
  
                  }
                              console.log("Async Test1")
              }).catch(err=&gt;
              {
  
                  console.log(err);
                  return res.status(500).json({
                      message:"Finding Chef Database Error!",
                      error: err
                  });
              });
  
          }
          console.log("Async Test2")
          console.log(all_recipe);
          return res.status(200).json(all_recipe);
  </code></pre>
  
  <p>Debug Console Out:</p>
  
  <pre><code>Async Test2
  []
  GET /store/ABC%20Pizza%20Store/getAllMenu 200 179.642 ms - 2
  Async Test1
  Async Test1
  Async Test1
  </code></pre>
  
  <p><strong>Solution</strong>
  Added Async/Await for Promise:</p>
  
  <pre><code>storeSchema.findOne(req.params,"chefs").exec()
  .then(async result=&gt;{
      if(result.length&lt;1)
      {
  
          return res.status(409).json({
              error_code:20,
              message:"Store not registered by Manager yet"
          });
      }
      else
      {
  
          let all_recipe= []
          for(let i =0; i&lt;result.chefs.email.length; ++i)
          {
              try{
  
  
                  let recipes = await chefSchema['chef'].findOne({"email":result.chefs.email[i]},"recipe").exec();
                  if(recipes!=null)
                  {
  
                      if(recipes.recipe.length!=0)
                      {
                          all_recipe.push(recipes.recipe);
                      }
  
                  }
              }
              catch(err)
              {
                  return res.status(500).json({
                  message:"getAllMenu Database Error!"
                  });
              }
  
          }
          console.log("Async Test2")
          console.log(all_recipe);
          return res.status(200).json(all_recipe);
  </code></pre>