views:

77

answers:

2

I guess this question isn't only specific to YUI, but that's the JS library I'm using and a specific answer would be helpful.

Basically when loading a page, I want a script to run a few XHRs using Y.io, and if they all return the data successfully then I want the script to move on to the next step, which will manipulate the data received.

I can think of a few ways of doing this, but they all seem a bit clumsy to me and I hope someone has a better suggestion. My ideas so far:

  1. Consolidate all the data I want into one JSON response, so if that one request is good, move on. (This is the solution I like least).
  2. When the first Y.io request returns successful, call the next, and so on, and when the last is successful then I know everything succeeded and move on to the next step of the script.

Any better ideas out there? I'm not really liking either of mine at the moment, but I'm leaning towards option two.

+1  A: 

Both implementations have merit:

  1. This method reduces the amount of transactions which reduces transport overhead
  2. This method possibly reduces the total amount of data transferred over the wire and reduces UI lag time by allowing the client side to get to work sooner while other requests are in queue.

JavaScript lends itself to either of these methods. The first is straight forward, the second can be done by chaining callbacks.

If you need/can start processing data sooner than later, the second method is preferable. If you require all of the data before processing, then the first method is required. It really all depends on your situation. Generally, if you can swing it, the second method (multipart as opposed to one large response) is preferable.

Justin Johnson
I'm not sending across a LOT of data, but I think the second method is better too since I can process parts separately as they come in. Thanks!
hora
+2  A: 

You shouldn't need to queue the Y.io calls. Just send them all at once and when they all return, move on.

var data = {};

function step(id, o, part) {
    try {
        data[part] = Y.Lang.JSON.parse(o.responseText);

        if (data.a && data.b && data.c) {
            processData(data);
        }
    }
    catch (e) {
        /* handle bad JSON, failure case */
    }
}

Y.io(a_url, { on: { success: step }, 'arguments': 'a' });
Y.io(b_url, { on: { success: step }, 'arguments': 'b' });
Y.io(c_url, { on: { success: step }, 'arguments': 'c' });
Luke
Thanks, I was hoping something like this was possible.
hora