Titanium Community Questions & Answer Archive

We felt that 6+ years of knowledge should not die so this is the Titanium Community Questions & Answer Archive

How to avoid multiple nested XHRs?

I'm finding myself progressively caught up in XHR loops when building dynamic windows/tables eg:

var xhr1 = Titanium.Network.createHTTPClient();
xhr1.onload = function()
{
     var xhr1JSON = JSON.parse(this.responseText);
     var xhr2 = Titanium.Network.createHTTPClient();
     xhr2.onload = function()
     {
          var xhr2JSON = JSON.parse(this.responseText);
          var xhr3 = Titanium.Network.createHTTPClient();
          xhr3.onload = function()
          {
               var xhr3JSON = JSON.parse(this.responseText);
          }
          xhr3.open();
          xhr3.send();
     }
     xhr2.open();
     xhr2.send();
}
xhr1.open();
xhr1.send();

If each of the JSON variables rely on the previous XHR request for their data, it seems like this continuous nesting is the only way to go. But it's getting awfully complicated in my project and I'm starting to get warnings about functions within functions.

Ideally I'd like to have one function that runs an XHR request and returns the response to a (hopefully, global) variable, but can't find similar examples.

Any suggestions would be most appreciated- thanks!

— asked June 27th 2010 by Ryan Marshall
  • iphone
  • titanium mobile
0 Comments

2 Answers

  • That's because you're using anonymous functions instead of named ones.

    You can also call http requests synchronously, though I have not tried that personally.

    — answered June 27th 2010 by Damien Elmes
    permalink
    0 Comments
  • This looks like it's exactly what I'm after:

    http://bradvernon.com/2010/03/titanium-mobile-synchronous-network-request-workaround/

    — answered June 28th 2010 by Ryan Marshall
    permalink
    0 Comments
The ownership of individual contributions to this community generated content is retained by the authors of their contributions.
All trademarks remain the property of the respective owner.