Titanium HTTPClient returns too 'fast'

好久不见. 提交于 2019-12-01 09:07:35

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

Aside from making the AJAX request synchronous (which you probably don't want), there isn't any way to return the data.

Whatever code relies on the response needs to be called from within the response handler.

Since functions can be passed around, you could have your getTasks method receive a callback function that is invoked and will receive the tasks 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();
    }

So you'd use it like this...

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.

}

You are getting empty alert because when the bottom alert is executed the server response is not available and tasks array is empty.

When the server response comes the tasks array is populated by the code which you have in the onload handler so you see the tasks in the second alert.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!