我正在为 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()
时功能如下:
function putToVar(results,arrayDim)
{
//Process Results
//Store in Array[arrayDim] the required value
}
我希望我已经说清楚了。 我已阅读以下帖子
- How do I pass multiple arguments into a javascript callback function?
- passing arguments to callback
- How to explain callbacks in plain english? How are they different from calling one function from another function?
- How to pass additional arguments to callbacks and also access default parameters?
但他们似乎都没有使用 .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
内。
我希望这是清楚的,如果不是,请告诉我。
测试一下!
干杯,来自玻利维亚拉巴斯
关于javascript - 使用 .execute() 时如何将附加参数传递给 JavaScript 中的回调函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21011405/