1

I'm trying to write a function in Javascript (with jQuery, if you want):

function fetchItem(itemId) { return /* ??? */; }

This function relies on a second, predefined and unmodifyable function that looks like this:

function load(callback) { /* ... */ }

This function is asynchronous. After calling it, it fetches n items via XHR, then when they have arrived, stores them in the DOM, then invokes the callback.

fetchItem uses a simple jQuery selector (irrelevant here) to check the DOM for the element with itemId and calls load if the item isn't there yet. Rinse and repeat.

My problem is that I want to wrap multiple asynchronous calls of load into my synchronous fetchItem function, which should return the DOM element with itemId after it has made enough load calls.

Pseudo code, if load was synchronous:

function fetchItem(itemId):
    while not dom.contains(itemId):
        load()
    return dom.find(itemId)

My first attempts at doing this in Javascript, which probably display a lot of misconceptions about Javascript's closures and execution model: ;)

function fetchItem(itemId) {
    var match = undefined;

    function finder() {
        match = $(...).get(0);
        if(!match) {
            load(finder);
        }
    }
    finder();

    return match;
}

Obviously, this fails because the return is executed before the first callback. Also, as you can see I had some problems getting match back out to fetchItem. Is it properly protected by the closure here? Would this work if fetchItem was executed multiple times in parallel, assuming that load supports this (and doesn't mix up the DOM)?

I'm probably missing a perfectly good pattern here, but I don't really know what to google for...

4 Answers 4

2

You need to make fetchItems async too and provide it a callback, something like this should probably work (warning untested!):

function fetchItems(itemIDS, callback, matches) {
    if (!matches) { // init the result list 
        matches = [];
    }

    // fetch until we got'em all
    if (itemIDS.length > 0) {
        var id = itemIDS[0]; // get the first id in the queue
        var match = $(id).get(0);

         // not found, call load again
        if (!match) {
            load(function() {
                fetchItems(itemIDS, callback, matches);
            });

        // found, update results and call fetchItems again to get the next one
        } else {
            matches.push(match); // push the current match to the results
            itemIDS.shift(); // remove the current id form the queue
            fetchItems(itemIDS, callback, matches);
        }

    // we have all items, call the callback and supply the matches
    } else {
        callback(matches);
    }
}

fetchItems(['#foo', '#bar', '#test'], function(matches) {
    console.log(matches);
})
1

I would simply gave your fetchItem function as a callback to load. Like this:

function fetchItem(itemId, callback):
    if not dom.contains(itemId):
        load(fetchItem)
    else:
        callback(dom.find(itemId))

callback() is a function that does rest of the job when necessary element appears in the DOM.

0

That is impossible. You cannot create synchronousness from asynchronousness. Why do not you add a callback to your fetchItem-function as well?

4
  • The callback itself creates synchronousness from the asynchronous routine does it not? One thing happening after the other.
    – Orbling
    Nov 25, 2010 at 19:54
  • @Orbling: No, it does not. You cannot predict which of two asynchronous calls finishes first (that would be synchronous).
    – jwueller
    Nov 25, 2010 at 20:10
  • No, but you can setup your code so that a given piece of code follows an asynchronous call, or even after multiple asynchronous calls have taken place. The only point of doubt is the order of return when multiple async calls are started.
    – Orbling
    Nov 25, 2010 at 20:19
  • Well, you can always poll and wait and that way synchronize the calls. But yeah, I guess another callback is the way to go. I just need to get used to my core logic being torn apart into multiple functions. Nov 25, 2010 at 21:19
0

Seems like everybody agrees that I need to introduce my own callback, so here's my (so far final) working solution:

var MAX_FETCH_MORE = 3;

/*
 * Searches for itemId, loading more items up to MAX_FETCH_MORE times if necessary. When
 * the item has been found or the maximum reload count has been reached, the callback
 * is invoked, which is passed the DOM object of the item wrapped in a jQuery object, or
 * undefined.
 */
function executeWithItem(itemId, callback, fetchCycleCounter) {
    // initialize fetchCycleCounter on first iteration
    if(!fetchCycleCounter) fetchCycleCounter = 0;
    console.debug('iteration ' + fetchCycleCounter + '/' + MAX_FETCH_MORE);

    // try to find the item in the DOM
    match = $('div[data-item-id="' + itemId + '"]').get(0);
    if(match) {
        // if it has been found, invoke the callback, then terminate
        console.debug('found: ' + match);
        callback($(match));
    } else if(!match && fetchCycleCounter < MAX_FETCH_MORE) {
        // if it has not been found, but we may still reload, call load() and pass it
        // this function as the callback
        console.debug('fetching more...');
        load(function() {executeWithItem(itemId, callback, fetchCycleCounter+1);});
    } else {
        // give up after MAX_FETCH_MORE attempts, maybe the item is gone
        console.debug('giving up search');
    }
}

// example invocation
executeWithItem('itemA01', function(item) {
    // do stuff with it
    item.fadeOut(10000);
});

Thanks to everybody for encouraging me to introduce another callback, it hasn't turned out looking so bad. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.