I'm trying to make a basic blocking function, an initialization function that needs to finish before any requests are made. There doesn't seem to be any built-in ways to do that, though - I was hoping for something like OCaML's Async library.
Asked
Active
Viewed 42 times
0
-
This is a little vague, providing more details will help you get better answers. – ccnokes Jul 29 '15 at 03:15
2 Answers
0
I'm not really clear on what you're trying to do. If you expand your question I'll adjust my answer accordingly.
Here's a couple general ideas on stringing together async/sync functionality:
AJAX calls can be set to be synchronous like so:
jQuery.ajax({
....
async: false
});
Or you can use promises (called Deferreds in jQuery) to string together order dependent async calls, like so:
var d1 = $.Deferred();
var d2 = $.Deferred();
$.when( d1, d2 ).done(function ( v1, v2 ) {
console.log( v1 ); // "Fish"
console.log( v2 ); // "Pizza"
});
setTimeout(function() {
d1.resolve( "Fish" );
}, 200);
setTimeout(function() {
d2.resolve( "Pizza" );
}, 300);
(The above example is adapted from https://api.jquery.com/jQuery.when/)
Also see How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?
0
You can use jQuery .when .then constructs to ensure everything is ready before running your app.
function longRunningAsynchronousAction() {
return $
.ajax({
url: "https://query.yahooapis.com/v1/public/yql",
dataType: "jsonp",
data: {
q: "show tables",
format: "json"
}
}).done(function() {
console.log('data loaded');
});
}
function initialize(onDoneFn) {
$
.when(
longRunningAsynchronousAction(),
longRunningAsynchronousAction(),
longRunningAsynchronousAction()
)
.then(onDoneFn);
}
function runApp() {
console.log('Starting app');
}
initialize(runApp);
Example as jsbin

jonjitsu
- 56
- 3