繁体   English   中英

为什么我的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); 
 });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM