Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concept - Designing a collapsible queue for asynchronous resources

Tags:

javascript

I've noticed that the size of a file requested will effect how long the response takes for ajax calls. So if I fire 3 ajax GET requests for files of varying size, they may arrive in any order. What I want to do is guarantee the ordering when I append the files to the DOM.

How can I set up a queue system so that when I fire A1->A2->A3. I can guarantee that they are appeneded as A1->A2->A3 in that order.

For example, suppose A2 arrives before A1. I would want the action to wait upon the arrival and loading of A1.

One idea is to create a status checker using a timed callback as such

// pseudo-code
function check(ready, fund) {
    // check ready some how
    if (ready) {
        func();
    } else {
        setTimeout(function () {
            check(ready, fund);
        }, 1); // check every msec
    }
}

but this seems like a resource heavy way, as I fire the same function every 1msec, until the resources is loaded.

Is this the right path to complete this problem?


1 Answers

status checker using a 1msec-timed callback - but this seems like a resource heavy way; Is this the right path to complete this problem?

No. You should have a look at Promises. That way, you can easily formulate it like this:

var a1 = getPromiseForAjaxResult(ressource1url);
var a2 = getPromiseForAjaxResult(ressource2url);
var a3 = getPromiseForAjaxResult(ressource3url);

a1.then(function(res) {
    append(res);
    return a2;
}).then(function(res) {
    append(res);
    return a3;
}).then(append);

For example, jQuery's .ajax function implements this.

like image 151
Bergi Avatar answered Jan 02 '26 02:01

Bergi