【问题标题】:I need wait for HTTP response我需要等待 HTTP 响应
【发布时间】:2016-05-03 12:40:55
【问题描述】:

我需要做几次阅读 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();
    ......
}

有什么建议吗??谢谢

【问题讨论】:

标签: javascript http appcelerator appcelerator-titanium


【解决方案1】:

在回调中你能不能只传递函数,当它被加载时继续你的代码。

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

【讨论】:

  • 感谢 Riddell,它运行良好
  • 欢迎您。很高兴它帮助我快速敲出 VS Code 中的附加代码,很高兴它没有任何问题。
猜你喜欢
  • 2015-12-28
  • 2017-11-19
  • 1970-01-01
  • 1970-01-01
  • 2021-06-30
  • 2016-05-26
  • 1970-01-01
  • 2011-12-22
  • 2021-01-30
相关资源
最近更新 更多