title: Chaining multiple async functions where one depends on another in Javascript/ Nodejs, Mongoose
body: <p>I have two functions that depend on each other. After my user saves his profile, I first have a function that saves his location and then returns its id, which I then use to update the user. But after trying a lot of combinations I couldn't get it to work properly. I'll list below what I tried.</p>
  <pre><code>async function NewUserProfileUpdate(req) {
      try {
          const loc_id = LocationController.AddUserLocation(req.body.location.longitude
              , req.body.location.latitude, req.query.id)
  
          loc_id.then((id) =&gt; {
              logger.info(&quot;Then &quot; + id)
              UserModel.User.updateOne({ user_id: req.query.id }, {
                  gender: req.body.gender, name: req.body.name, bio: req.body.bio,
                  location_id: id
              })
          })
  
      } catch (err) {
          return err
      }
  }
  </code></pre>
  <pre><code>async function AddUserLocation(longitude, latitude, userID) {
      const location = { type: 'Point', coordinates: [longitude, latitude] }
  
      await LocationModel.create(
          { user_id: userID, location: location }, function (err, loc) {
              if (err) {
                  return err;
              }
              logger.info(&quot;Created + &quot; + loc._id)
              return loc._id
          });
  }
  </code></pre>
  <p>Then is called before create</p>
  <pre><code>info: Then undefined {&quot;service&quot;:&quot;user-service&quot;}
  info: Created + 5feb3174f70c08f9543fdc49 {&quot;service&quot;:&quot;user-service&quot;}
  </code></pre>
  <p>I tried using events, chaining it with then =&gt;, chaining with asyncs (idk why this doesnt work, I had async for loc_id, and that should wait until loc_id returns but it doesnt), I tried different combinations of regular functions and asyncs but nothing gave me the desired result. (I have gotten a result using async and events but without listeners, I have no idea what happened there)</p>