为什么我在 JavaScript 中的回调不适用于异步结果
Why is my callback in JavaScript not working for asynchronous results?
我一直在尝试设置回调以从异步操作中获取结果,但到目前为止我没有成功。看看下面代码的结构。
var markers = []; //global array
//The callback parameter is a reference to the function which is passed as an argument from the doAsyncOperation call
function doAsyncOperation(callback) {
var xmlArray = []; //the array that will hold the data that I'm trying to access later in the code
downloadUrl("theXmlFile.xml", function (data) { //this is the async code that stores the results in an array called xmlArray
var xmlItems = data.documentElement.getElementsByTagName("row");
xmlArray.push(theData); //this array is populated with data within this async code block
//the logic works here; this part is not the issue
});
setTimeout(function () {
callback(xmlArray); //passing xmlArray as the result
}, Math.random() * 2000);
}
//the code below is the function call that should be getting the results from the doAsyncOperation function
doAsyncOperation(function (xmlData) {
alert(xmlData); //I am not able to see the data in xmlArray here
});
//the function below is called on Window.onload
function initialize() {
//In this function, I need to use the results in the xmlArray above.
//I have tried saving the results into a global array, but it doesn't work because this function is called
//before the async operation completes.
}
总而言之,我在访问异步操作的结果时遇到问题。如您所见,我尝试设置回调来访问数据,但我一定做错了什么。我在这里看过类似的问题,但似乎没有一个能解决我遇到的问题。任何帮助,不胜感激。
您有两个名为 xmlArray
的变量。
一个是在doAsyncOperation的范围内。
另一个是在匿名函数的范围内,您作为参数传递给downloadUrl
。
它们都是从分配空数组开始的。
第二个有一些项目被推入其中。
第一个是你传递给callback
删除行
var xmlArray = []; //this array is populated with data within this async code block
如果您希望匿名函数中的代码改为修改第一个数组。
注意:由于您在发送请求后尝试处理数据Math.random() * 2000
,因此在尝试将其传递给callback
之前,您可能没有收到响应(触发匿名函数)。
这
不应该像下面这样吗 - downloadUrl
完成后调用callback
function doAsyncOperation(callback) {
var xmlArray = [];
downloadUrl("theXmlFile.xml", function (data) {
var xmlItems = data.documentElement.getElementsByTagName("row");
xmlArray.push(theData);
callback(xmlArray);
});
}
doAsyncOperation(function (xmlData) {
alert(xmlData);
});
相关文章:
- html5 drawImage适用于firefox,而不是chrome
- Jquery Ajax POST不工作.适用于GET
- 如何调试遗留的javascript代码(适用于IE,但在Google Chrome中不正常)
- .load()适用于window,而不是ID
- 使用Jquery更改css样式适用于id's、 不在课堂上
- 提交按钮不会;不适用于Chrome或Firefox,但适用于Internet Explorer
- 为什么 javascript 中的“btoa”编码适用于 20 位字符串而不是 20 位整数
- Javascript String to Date适用于Chrome,而不是FF或Safari
- Onchange,向上,向下箭头键适用于FF和Chrome,但在IE中不起作用
- .load() 适用于 IE 和 dreamweaver 预览版,但不能使用 opera 和 chrome
- 找不到适用于 Highcharts 的 JSON 数组语法
- 为什么在jQuery中使用focusout适用于Firefox,而使用addEventListener则不适用;t
- jQuery选择菜单验证器适用于FF和Chrome,但不适用IE
- 单选按钮'onclick'适用于Chrome和Firefox,但不适用IE
- JQuery ScrollTop适用于chrome,但不适用firefox
- window.opener.location.href适用于IE,但不适用Chrome或Safari
- Frame Busting buster不完全适用于IE
- Jquery touch punch适用于Chrome和Firefox,但不适用IE
- 背景更改仅适用于chrome+$.预加载不适用;不起作用
- JavaScript window.location.replace适用于Firefox,但不适用IE或Chrome