2016-05-03 9 views
0

Ich muss mehrere Messungen HTTP, und ich muss auf Antwort warten. Aber HTTP ist asynchron. Dann weiß ich nicht wie.Ich muss auf HTTP-Antwort warten

mein Code:

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(); 
    ...... 
} 

Jeder Vorschlag ?? Danke

+0

Sie verwenden NodeJS? Wenn ja, glaube ich, dass Sie eine Bibliothek wie [async] (https://github.com/caolan/async) benötigen, um auf mehrere Aufrufe warten zu können, und starten Sie dann einen Rückruf. –

+1

Mögliches Duplikat von [Wie gebe ich das zurück? Antwort von einem asynchronen Anruf?] (http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Idos

Antwort

2

Auf dem Rückruf können Sie nicht einfach die Funktion übergeben und wenn es geladen ist mit Ihrem Code fortfahren.

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

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

oder man könnte es auf diese Weise tun:

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(); 
    ...... 
} 
+0

Danke Riddell, es läuft gut –

+0

Ihr Willkommen . Ich bin froh, dass es mir geholfen hat, den zusätzlichen Code in VS Code so schnell aufzuladen, dass er ohne Probleme funktioniert hat. – Riddell