javascript - 为什么我的 JavaScript 回调不能用于异步结果?

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

总而言之,我在访问异步操作的结果时遇到了问题。正如您所看到的,我尝试设置回调来访问数据,但我必须做错什么。我在这里看过类似的问题,但它们似乎都没有解决我具体遇到的问题。任何帮助表示赞赏。

最佳答案

您有两个名为 xmlArray 的变量。

其中一个在 doAsyncOperation 的范围内。

另一个位于您作为参数传递给 downloadUrl 的匿名函数的范围内。

它们都是从分配给它们的空数组开始的。

第二个有一些项目被插入其中。

第一个是您传递给回调的那个

删除该行

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

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

<小时/>

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

关于javascript - 为什么我的 JavaScript 回调不能用于异步结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35135163/

相关文章:

javascript - 访问 ng-repeat 的项目范围

c# - 在 c# 5.0 中, "async/await"函数是否总是在运行开始时在主线程上运行

node.js - 如何从NodeJS中的函数返回Post请求的响应?

android - 协程 : Runblocking freeze Android UI

javascript - 使用 takeUntil 在 Redux-observable 中取消异步请求的预期行为是什么

javascript - 在 react 功能组件中使用 useEffect 时出错

javascript - 如何缓存另一个站点的 iframe?

javascript - 在javascript中对对象进行升序排序

javascript - 了解从 CoffeeScript 中的拼接返回的结果

javascript图像 slider 开始