簡體   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