开发者

What's the best way to call a function in YUI3 only if a series o XHR (IO) requests are successful?

开发者 https://www.devze.com 2022-12-13 04:19 出处:网络
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.

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 开发者_Python百科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.


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' });


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消