title: jQuery axax lifecycle and response in ASP.NET MVC application or API in general
body: <p>I need a clarification on jQuery Ajax lifecycle when calling an endpoint, in my specific case an ASP.NET MVC (Net core/Net 5) application.</p>
  <p>What I specifically need is to know how the success/error event chain works and when exactly the control is returned to jquery once the http call is fired.</p>
  <p>Let's imagine a jquery ajax like this</p>
  <pre><code>postData = JSON.stringify({test: 1, anotherVariable : &quot;YEEEE&quot;});
  $.ajax({
              url: '@Url.Action(&quot;MyAspNetAction&quot;, &quot;MyAspNetController&quot;)',
              type: &quot;POST&quot;,
              contentType: 'application/json; charset=utf-8',
              dataType: &quot;json&quot;,
              data: postData,
              success: function (result) {
                  showMessage(result.responseText, result.success ? 'success' : 'error', 3000)
              },
              error: function (error) {
                  showMessage(result.responseText, 'success', 3000)
              }
          });
  </code></pre>
  <p>On the server I have an async Task controller which we could define as:</p>
  <pre><code> public async Task&lt;JsonResult&gt; MyAspNetAction([FromBody] MyAspNetActionModel){
      try{
          await someLongAction();
          return some jsonresult { success = true, responseText = &quot;HELLO&quot;}
      }
      catch(Exception ex)
      {
           return some jsonresult { success = false, responseText = &quot;ERROR&quot;}
      }
  }
  </code></pre>
  <p>which gets executed async from asp net (I guess).</p>
  <p>Now, Let's suppose I do various risky task in this action, like manipulating</p>
  <pre><code>HttpContext.Session[&quot;key&quot;]
  ViewData[&quot;Key&quot;]
  </code></pre>
  <p>calls to other async stuff which takes some time to get executed (let's say 30 seconds for the sake of putting up a worst-case scenario.</p>
  <p>All this togheter.</p>
  <p>Now,
  WHEN javascript gets control back and WHEN SUCCESS???</p>
  <p>Am I handling this right?</p>
  <p>I mean, all that async stuff is happening (ajax async, mvc action is async and so on.
  Will the jquery action go to succes only after my MVC action is completed and gets the result?</p>
  <p>Or the mere fact that jquery ajax managed to call my action will result in a HTTP 200 (so it's ok/success) and it will ignore all the code called inside, which has to be handled in another way, and the following javascript will be executed?</p>
  <p>Basically I want to know if I can execute all the code in the MVC action being sure that ajax will enter in succes/error only when the action completed all the code</p>
  <p>AND</p>
  <p>if the javascript following the jquery ajax will continue executing and the control to the ajax action will return later</p>