Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow jQuery.ajax.settings.beforeSend to handle async promises #2600

Closed
pensierinmusica opened this issue Sep 18, 2015 · 3 comments
Closed
Labels

Comments

@pensierinmusica
Copy link

Hi,

Currently jQuery.ajax.settings.beforeSend only works with sync code. It would be nice if it could support async code too.

Let's look at a code example. Imagine I need the value of foo to be added to all jQuery Ajax request headers in my app.

$.ajaxSetup({
  beforeSend: function (req) {
    if (localStorage.foo) {
      // Sync version - "foo" is locally available
      req.setRequestHeader('foo', localStorage.foo);
    } else {
      // Async version - "foo" needs to be fetched from an API server
      return $.get({
        url: '/foo',
        beforeSend: null
      })
        .done(function (data) {
          localStorage.foo = data;
          req.setRequestHeader('foo', data);
        });
    }
  }
});

As the web is moving more and more to async operations, imho it would make sense to support this pattern in jQuery. Thoughts?

Thanks!

@pensierinmusica pensierinmusica changed the title Allow jQuery.ajax.settings.beforeSend to return a promise Allow jQuery.ajax.settings.beforeSend to handle async promises Sep 18, 2015
@markelog markelog added the Ajax label Sep 18, 2015
@markelog
Copy link
Member

See #2532 (comment)

Sorry

@dmethvin
Copy link
Member

This doesn't need to be done (and IMO shouldn't be done) inside $.ajax(), just create your memoizing function and call that. Using $.ajaxSetup() is definitely a bad idea unless you have written and understand every ajax call that will be made through these new semantics.

@pensierinmusica
Copy link
Author

unless you have written and understand every ajax call that will be made through these new semantics.

@dmethvin, yep, that's exactly the case at hand. Anyways, this is what I ended up doing, although I wish jQuery Ajax could provide a better / async way to handle these situations:

http://stackoverflow.com/questions/32643469/jquery-how-to-make-ajaxsend-wait-for-another-ajax-response-before-proceeding

Cheers

@lock lock bot locked as resolved and limited conversation to collaborators Jun 19, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Development

No branches or pull requests

3 participants