AmpersandJS / ampersand-sync

Provides sync behavior for updating data from ampersand models and collections to the server.
http://ampersandjs.com
MIT License
20 stars 28 forks source link

Is it possible to defer a request in beforeSend or ajaxConfig? #34

Closed juice49 closed 9 years ago

juice49 commented 9 years ago

I have had a look at the source for ampersand-sync and xhr, and it seems that ultimately when beforeSend is called in xhr, no control over when the request is actually sent is ceded to it.

I suspect this is something that is related to the xhr module, rather than ampersand-sync, but I wonder if anybody has encountered this before.

My specific use case is that occasionally I need to fetch a new access token from an API before a request is made. If either ajaxConfig or beforeSend waited for a callback to continue, I could first fetch my access token, set it for the pending request and continue.

herkyl commented 9 years ago

Any updates on this? I have the same issue where I occasionally need to fetch a new access token.

codepunkt commented 9 years ago

Same here.

naugtur commented 9 years ago

Hi, I'm one of the maintainers of xhr and recently a contributor here.

beforeSend is available in ampersand-sync mostly as a legacy from backbone/jQuery.ajax and the original one is also synchronous. I'm pretty sure that for the sake of adoption etc. it'd be better if we didn't start requiring it to call a callback when done. (for the same reason I would consider aborting on return false https://github.com/Raynos/xhr/issues/83)

It's been a while and you probably found a workaround. Would you like to share?

It could probably be hacked like this (not tested):

beforeSend: function(xhr){
  var origSend = xhr.send;
  xhr.send=function(body){
    //do async magic, and then call:
      origSend.call(xhr,body)
  }
}
juice49 commented 9 years ago

@naugtur Ah, that looks perfect! Thank you!

My workaround is very inelegant; it involves occasionally requesting a new access token while the client has a valid refresh token. The logic to do this in an offline available single page app with many forms was quite horrible!

Switching to this solution will eliminate a bunch of code and hoops to jump through. Thanks for for the help, it is much appreciated! 😊