0

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.

linkhyrule5
  • 871
  • 13
  • 29

2 Answers2

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?

Community
  • 1
  • 1
ccnokes
  • 6,885
  • 5
  • 47
  • 54
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