javascript - 我需要等待 HTTP 响应

标签 javascript http appcelerator appcelerator-titanium

我需要多次读取 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();
    ......
}

有什么建议吗?谢谢

最佳答案

在回调中,您不能只传递函数,并在加载函数时继续执行您的代码。

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

关于javascript - 我需要等待 HTTP 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37004442/

相关文章:

http - Docker 路由/反向代理问题,无法 curl 其他容器

javascript - 从多行表 PHP Javascript 将多条记录插入 MySQL

javascript - Node.js 发送后无法设置 header 引入 res.render() 后出现错误

http - Dart 2.1 中的 HTTP 包发生了什么?

c - HTTP 持久连接

android - 移动应用程序中的用户身份验证

javascript - 加速器。检测导航栏标题上的点击

ios - 无法将存档导出到 ipa(未找到适用的设备)

javascript - 从 Node.js 更新客户端 DOM

javascript - 让 jReject 工作的问题