簡體   English   中英

使用.execute()時如何將附加參數傳遞給javascript中的回調函數?

[英]How to pass additional arguments to callback functions in javascript when using .execute()?

我正在使用適用於Google Analytics(分析)API的JavaScript,但我不過是JS的新手。 我具有C ++和Java知識,可以與邏輯思維相處,但是有些事情使我感到困惑。 在GA API中,我可以進行如下函數調用:

gapi.client.analytics.data.ga.get({'ids':'<tableID>',
    'start-date':'<startDate>',
    'end-date':'<endDate>',
    'metrics':'<metrics>',
    'filters':'<filters>',
    'samplingLevel':'HIGHER_PRECISION',}).execute(putToVar);

putToVar()是用戶定義的函數,其定義如下:

function putToVar(results)
{
    //do processing with the results
}

據我了解, .execute()方法用於為異步調用gapi.client.analytics.data.ga.get()調用回調函數。 所以我想什么function1().execute(function2)所做的就是調用function2與返回值function1作為參數? 這個對嗎?

我處於一種情況下,無論API調用是否返回了結果對象(這是一個異步調用,因此我都不知道),我都需要應用幾個不同的過濾器並將它們存儲在數組中以在需要時按需進行檢索當響應到來時,它僅對回調函數可見)。

我想將存儲返回的對象的數組的尺寸傳遞給回調函數,以便以后可以按需檢索它們,而不必擔心響應的處理順序。 我之所以這樣說,是因為最初我嘗試了for循環,並且獲得對API調用的響應的順序與為查詢放置API調用的順序不同,因此存在不匹配的情況。

由於引用使用此方法來調用回調函數,因此我想知道在使用.execute()方法時如何將其他參數傳遞給這樣的回調函數,當我編寫putToVar()函數putToVar()像這樣:

function putToVar(results,arrayDim)
{
    //Process Results
    //Store in Array[arrayDim] the required value
}

我希望我已經說清楚了。 我已閱讀以下帖子

但他們似乎都沒有使用.execute()方法,而且我無法弄清楚如何使用他們所說的內容。 或者,是否以及如何.execute()方法(回調執行的類型)以幫助實現我的目的。

添加一個閉包將解決您的問題:

for(var x = 0; x< n x ++){  //Or any other loop
   (function(x){   //Closure. This line does the magic!!
       var arrayDim = something_that_depends_on_x_or_the_loop,
           param2 = some_other_thing_that_depends_on_x;
       gapi.client.analytics.data.ga.get({'ids':'<tableID>',
         'start-date':'<startDate>',
          ...
       }).execute(function putToVar(results){   //this fn is defined inline to get access to param1, param2
           //The following alerts will use the *correct* variables thanks to the closure
           alert(x);
           alert(arrayDim);
           alert(param2);
       });
   })(x); //This one too
}

封口起到了神奇的作用。 它將允許每個循環周期都有自己的變量(不共享),因此正確的變量將在執行時放在putToVar

我希望很清楚,如果沒有,請告訴我。

只是測試!

來自玻利維亞拉巴斯的歡呼聲

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM