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

Why is my callback in JavaScript not working for asynchronous results?

本文关键字:不适用 适用于 异步 结果 回调 JavaScript 为什么      更新时间:2023-09-26

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

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