2016-05-03 24 views
0

私はいくつかの読み取りHTTPを行う必要があり、私は応答を待つ必要があります。しかし、HTTPは非同期です。それから私はどのように知りません。私はHTTP応答を待つ必要があります

私のコードは次のとおりです。

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

任意の提案?ありがとう

+0

あなたはNodeJSを使用していますか?もしそうなら、あなたは[async](https://github.com/caolan/async)のようなライブラリが必要だと思って、いくつかの呼び出しが完了するのを待ってから、コールバックを起動します。 –

+1

[非同期呼び出しからの応答?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Idos

答えて

2

コールバックでは、関数を渡すだけでなく、ロード時にコードを続行できますか?

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

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

またはあなたはそれをこのように行うことができます:

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

ありがとうリドル、それは正常に実行されます –

+0

ようこそ。うれしいことに、すぐにVSコードで追加のコードをノックして、問題なく動くことができてうれしいです。 – Riddell

関連する問題