0

i need to do several readings HTTP, and i need wait for response. But HTTP is async. Then i don't know how.

my code is:

var clientelee = Ti.Network.createHTTPClient({
    // function called when the response data is available
    onload : function(e) {
        Ti.API.info("*******      Recibido: " + this.responseText);
    },
    // function called when an error occurs, including a timeout
    onerror : function(e) {
        Ti.API.debug("****** ERROR *********"+e.error);
    },
    onreadystatechange: function(e){
        Ti.API.info("******* STATUS *********"+e.readyState);
    },
    timeout : 3000  // in milliseconds
});

function LeeDatos(){
    url = "http://www.hola.com/read/"+leoSerie;
    // Prepare the connection.
     clientelee.open("GET", url);
     // Send the request.
     clientelee.send();     
}


for (i=0;i<NRegistros;i++){
    TablaSerieTermostatos[i]=rows.field(0);
    leoSerie=rows.field(0);
    LeeDatos();
    ......
}

Any suggestion?? Thanks

Fokke Zandbergen
  • 3,866
  • 1
  • 11
  • 28
Karlos Garcia
  • 174
  • 3
  • 16
  • Are you using NodeJS? If so, I believe you need a library like [async](https://github.com/caolan/async), to wait for several calls to complete, and then launch a callback – Jeremy Thille May 03 '16 at 12:47
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Idos May 03 '16 at 12:49

1 Answers1

2

On the callback could you not just pass function and when it's loaded continue with your code.

 onload : function(e) {
    Ti.API.info("*******      Recibido: " + this.responseText);
    LoadedData();
 },

function LoadedData() {
    // Data loaded from ASYNC Carry on...
}

or you could do it this way:

function waitForResponse( type, url, callback ) {

    var client = Ti.Network.createHTTPClient({
        // function called when the response data is available
        onload : function(e) {
            Ti.API.info("*******      Recibido: " + this.responseText);
            callback();
        },
        // function called when an error occurs, including a timeout
        onerror : function(e) {
            Ti.API.debug("****** ERROR *********"+e.error);
        },
        onreadystatechange: function(e){
            Ti.API.info("******* STATUS *********"+e.readyState);
        },
        timeout : 3000  // in milliseconds
    });

    client.open(type, url);

    client.send(); 
}

function LeeDatos(){
    url = "http://www.hola.com/read/"+leoSerie;

     waitForResponse( "GET", url, function() {
        // Data Ready... 
     });  
}

for (i=0;i<NRegistros;i++){
    TablaSerieTermostatos[i]=rows.field(0);
    leoSerie=rows.field(0);
    LeeDatos();
    ......
}
Riddell
  • 1,429
  • 11
  • 22