views:

46

answers:

1

Does jQuery.ajax({async: false}) still use the XMLHttpRequest object?

If so, how is the request synchronous?

Is there just some mechanism inside the function definition that allows the asynchronous request put out by the XHR to be wrapped in a synchronous wrapper?

I ask because I want to wrap asynchronous function calls into a synchronous wrapper.

EDIT:

I want to do this for dependencies. I need to not run anything more until all the external dependency scripts are loaded, however, I'd rather not load each of the files synchronously.

Basically, I want this:

require(['lib1.js','lib2.js'])

Library1Function();
Library2Function();

To load lib1 and lib2 at the same time, but block until both are loaded.

I know I could do this with a callback, however that doesn't work if the files I'm including also have dependencies included in the same way.

EDITx2

Reason why callbacks don't work:

# lib2.js
window.Library2Function = function(input) {
  alert(input);
}

# lib1.js
require('lib2.js', function() {
  window.Library1Function = function() {
    window.Library2Function('Hi there');
  }
});

# main.js
require('lib1.js', function() {
  window.Library1Function();
});

The problem is that, in main.js, that callback will get sent off once lib1.js is loaded and run. The problem is, Library2Function isn't actually defined until lib2.js is loaded, which happens after lib1.js is parsed.

+1  A: 

Does jQuery.ajax({async: false}) still use the XMLHttpRequest object?

Yes.

XMLHttpRequest.prototype.open accepts async as its third parameter. If it's true (default), the request is asynchronous. Otherwise, it's synchronous.

I ask because I want to wrap asynchronous function calls into a synchronous wrapper.

Why do you want to do this? This will most likely result in more problems than it "fixes".

strager
See edit - I might accept your answer and move that to another question though.
Jamie Wong