多个 HTTP 客户端请求不存储会话数据

Multiple HTTP Client Requests not storing session data

我有一个问题,我想知道代码是否可以快速创建单独的会话 ID,让我详细说明。我有两个独立的 HTTP 客户端,它们一个接一个地执行(请参见下面的代码)。我遇到的奇怪问题是在第二个 HTTP 客户端请求中,我所做的只是检索一些会话数据。然而,有时 returns 数据正常,有时会话信息未定义,这会导致无穷无尽的问题。一旦我删除第二个 Http 客户端,问题就不再发生。

一些研究我认为这可能归结为异步客户端,我可以为下一个操作重新使用相同的 Http 客户端变量并保留会话数据吗?任何建议或知识将不胜感激。

this.login = function(username, password, loaded, failed, incorrect) {
        var xhr = Ti.Network.createHTTPClient({
            onload : function(e) {
                var response = this.responseText;
                switch(response) {
                case "1":
                    loaded();
                    break;
                case "0":
                    incorrect();
                    break;
                case "2":
                    incorrect();
                    break;
                case "3":
                    incorrect();
                    break;
                default:
                    failed();
                }
            },
            onerror : function(e) {
                failed(e);
            },
            timeout : 5000,
            validatesSecureCertificate : false
        });
        xhr.open('POST', this.url, true);
        xhr.send({
            'action' : 'login',
            'email' : username,
            'password' : password,
        });

        var getdb = Ti.Network.createHTTPClient({
            onload : function(e) {
                var response = this.responseText;
                Ti.App.Properties.setString('name', response);
            },
            onerror : function(e) {
                failed(e);
            },
            timeout : 5000,
            validatesSecureCertificate : false
        });
        getdb.open('POST', this.url, true);
        getdb.send({
            'action' : 'get_name',
            'device' : 'mobile'     
        });

    };

您的问题是您同时执行了两个调用。所以执行的顺序是未知的。您需要做的是在第一个完成后调用第二个。为此,您需要在第一个回调中添加第二个 http 调用。

为了让您的代码更有条理,我建议您使用函数!使其更具可读性。

function doBothCalls(){
    doFirstCallFunction(function(){
        doSecondCallFunction();
    }
}

然后doFirstCallFunction得到一个回调函数,这个回调函数你应该在第一个进入http回调后调用。

这里需要的是Javascript中的Promises

当你进行异步调用时,它们都是按随机时间顺序发生的,所以你不能进行依赖于同一执行上下文中另一个异步调用结果的异步调用(你在你的代码中这样做)

为了克服这个问题,Javascript 具有 promises 的功能,简而言之就是:

A Promise object represents a value that may not be available yet, but will be resolved at some point in the future. It allows you to write asynchronous code in a more synchronous fashion. For example, if you use the promise API to make an asynchronous call to a remote web service you will create a Promise object which represents the data that will be returned by the web service in future.