为什么我在JavaScript中的回调不适用于异步结果?

时间:2016-02-01 16:14:46

标签: javascript asynchronous

我一直在尝试设置回调以从异步操作中获取结果,但到目前为止我还没有成功。看看下面代码的结构。

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

总结一下,我无法访问异步操作的结果。正如您所看到的,我尝试设置回调来访问数据,但我必须做错事。我在这里看过类似的问题,但似乎没有一个问题可以解决我具体的问题。任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:1)

您有两个名为xmlArray的变量。

其中一个属于doAsyncOperation。

另一个是作为downloadUrl参数传递的匿名函数的范围。

它们都是通过分配空数组开始的。

第二个将一些物品推入其中。

第一个是您传递给callback

的那个

删除行

var xmlArray = []; //this array is populated with data within this async code block

如果您希望匿名函数中的代码改为修改第一个数组。

注意:由于您尝试在发送请求之后处理数据Math.random() * 2000,因此您可能在尝试之前未收到响应(触发匿名函数)将其传递给callback

答案 1 :(得分:1)

不应该如下所示 - 在callback完成后调用downloadUrl

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