[英]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.