Node.js wait until async functions are complete, then continue with the rest of the code
<p>In my code I have 2 for loops executing one async function (it's the same function in both loops), but the code, after these 2 loops, has to wait until the execution of them, before it runs. This is my code:</p>

<pre><code>for(var a = 0; a &lt; videoIds.length; a++){
  if(videoIds){
    findVideo(videoIds[a], function(thumbnailPath, videoName){ // findVideo is the async function
      // it returns 2 values, thumbnailPath and videoName
      videoNames[a] = videoName; // and then these 2 values are written in the arrays
      thumbnaildPaths[a] = thumbnailPath;
      console.log('1');
    });
  }
}

// then the above code runs one more time but with different values, so I won't include it here (it's the same thing)
enter code here
console.log('3');
// the rest of the code
// writes the values from the loops to the database so I can't run it many times 
</code></pre>

<p>If I run the code, I see 3 (from the console.log function) before I see 1. But as I stated above I have to wait for the loop to end before moving on. The <code>findVideo()</code> function just contains a Video.find({}) method provided by mongoose, and then returns the values thumbnailPath and videoName. What I need to do is wait for the 2 loops to end and then continue, but I can't have the rest of the code inside the loops for obvious reasons! Is there any way to fix this? Thank you!</p>