title: Nested Async javascript functions
body: <p>I am using waterline + sails for one api and i have the following function that has nested <code>exec()</code> calls. </p>
  
  <pre><code>AcademyService.getAll().exec(function (error, data) {
  
          if (error) {
  
              return res.json({result: false, message: error});
  
          }
  
          var academies = data;
  
          for (var i = 0; i &lt; Object.keys(academies).length; i++) {
  
              var user_id;
  
              user_id = academies[i].academy_user_id;
  
              (function (index) {
  
                  UserService.getOneById(user_id).exec(function (error, data) {
  
                      if (error) {
  
                          academies[index].academy_user_id = null;
  
                      }
  
                      academies[index].academy_user_id = data.user_fname+" "+data.user_lname;
  
                  });
  
              })(i);
  
          }
  
          return res.json({result: true, academies: academies});
  
      });
  </code></pre>
  
  <p>Problem with above code is that, the last return statement does not have updated <code>academies</code> object. i.e. it does not have the updated value for its <code>academy_user_id</code>. I attribute this to the asynchronous behaviour of the calls and i think the when we reach the last return, the async calls for <code>UserService</code> are still running in the loop and updated <code>academies</code> object is not passed on.</p>
  
  <p>Now, a hasty solution is to return the <code>academies</code> object from within the <code>UserService.getOneById</code> callback with a loop end check but that does not seem to be the right approach. So,can we somehow do the inner <code>exec()</code> synchronously?      </p>