编程语言
首页 > 编程语言> > javascript – Titanium HTTPClient返回’快’

javascript – Titanium HTTPClient返回’快’

作者:互联网

我有以下功能:

  getTasks: function()
    {
        var taskRequest = Titanium.Network.createHTTPClient();
        var api_url = 'http://myawesomeapi.heroku.com/users/' + Ti.App.Properties.getString("userID") + '/tasks';

        var tasks = [];
        taskRequest.onload = function() {
            var response = JSON.parse(this.responseText), 
            len = response.length,
            i = 0,
            t;

            for(; i < len; i++)
            {
                task = response[i];
                var newTask = {};
                newTask.rowID = i;
                newTask.title = task.title;
                newTask.description = task.description;
                newTask.id = task.id;
                newTask.hasChild = true;

                tasks.push(newTask);
            }

            alert(tasks);
        }

        taskRequest.open('GET', api_url, false);
        taskRequest.setRequestHeader('Content-Type', 'application/json');
        taskRequest.send();

        alert(tasks);
            // return tasks;
    }

这个功能在我的控制器中;当我需要加载数据时,我在我的视图中调用它.但是,我希望返回此数据,以便将其分配给视图中的变量.

现在发生的是它会让空虚回归.最后一个警报(底部一个)似乎运行得太快而且它返回一个空数组,而只有在onload函数完成后才会收到警报的那个包含我需要的内容.

现在我明显的问题是,如何让我的函数返回带有数据的数组,而不是没有?

把计时器放在上面似乎不是正确的决定..谢谢!

解决方法:

“However, I wish to return this data so I can assign it to a variable in the view.”

除了使AJAX请求同步(您可能不想要)之外,没有任何方法可以返回数据.

无论代码依赖于响应,都需要从响应处理程序中调用.

由于函数可以传递,你可以让你的getTasks方法接收一个被调用的回调函数,并接收任务Array.

  getTasks: function( callback ) // receive a callback function
    {
        var taskRequest = Titanium.Network.createHTTPClient();
        var api_url = 'http://myawesomeapi.heroku.com/users/' + Ti.App.Properties.getString("userID") + '/tasks';

        taskRequest.onload = function() {

            var tasks = [];

            // code populating the tasks array

            alert(tasks);

            callback( tasks ); // invoke the callback
        }

        taskRequest.open('GET', api_url, false);
        taskRequest.setRequestHeader('Content-Type', 'application/json');
        taskRequest.send();
    }

所以你要像这样使用它……

myObj.getTasks(function(tasks) {
    alert('in the callback');
    alert(tasks);
      // Any and all code that relies on the response must be
      //   placed (or invoked from) inside here
    some_other_function();
});

function some_other_function() {

    // Some more logic that can't run until the tasks have been received.
    // You could pass the tasks to this function if needed.

}

标签:javascript,return,appcelerator,titanium,httpclient
来源: https://codeday.me/bug/20191008/1871701.html