gpt4 book ai didi

javascript - Titanium HTTPClient 也返回 'fast'

转载 作者:行者123 更新时间:2023-11-29 15:01:45 24 4
gpt4 key购买 nike

我有以下功能:

  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;
}

这个函数在我的 Controller 中;当我需要加载数据时,我会在我的 View 中调用它。但是,我希望返回此数据,以便我可以将它分配给 View 中的变量。

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

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

设置计时器似乎不是正确的决定。谢谢!

最佳答案

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

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

任何依赖于响应的代码都需要从响应处理程序中调用。

由于函数可以传递,您可以让您的 getTasks 方法接收一个回调函数,该函数被调用并将接收 tasks 数组.

  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 - Titanium HTTPClient 也返回 'fast',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9056587/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com