title: jQuery: how to make ajaxSend wait for another Ajax response before proceeding?
body: <p>I'm using jQuery (v.3.0.0) and I need <a href="http://api.jquery.com/ajaxsend/" rel="nofollow">ajaxSend()</a> to check if a value is present in <code>localStorage</code>, to add it in the outgoing request headers.</p>
  
  <p>If the value is not present in <code>localStorage</code>, <code>ajaxSend()</code> should get this value with another Ajax request and then send the original request with the correct value in the headers.</p>
  
  <p><strong>This must be a global handler, that applies to all jQuery Ajax requests that are sent out.</strong></p>
  
  <p>Let's make a code example.</p>
  
  <pre><code>$(document).ajaxSend(function (ev, req, opts) {
    // Before sending any jQuery Ajax request
    var original = req;
    if (localStorage.foo) {
      // If value "foo" is available, add it to the headers
      req.setRequestHeader('foo', localStorage.foo);
    } else {
      // Otherwise get it first, and add it to the headers
      $.get({url: '/foo', global: false})
        .done(function (data, textStatus, req) {
          // "foo" is received and added to the original request headers
          localStorage.foo = data;
          original.setRequestHeader('foo', data);
          // Now the original request is ready to be sent
        });
    }
  });
  </code></pre>
  
  <p>When <code>foo</code> is not available, the problem with the code above is that obviously the original request is sent out before the value of <code>foo</code> is retrieved.</p>
  
  <p>Is there any way to fix this and get it to work properly?</p>
  
  <p>Thanks!!</p>