I'm working with javascript for Google Analytics API but I'm no more than a novice in JS. I have C++ and Java knowledge and I can get along with logical thinking but some things puzzle me. In GA API I get to make a function call like this:
gapi.client.analytics.data.ga.get({'ids':'<tableID>',
'start-date':'<startDate>',
'end-date':'<endDate>',
'metrics':'<metrics>',
'filters':'<filters>',
'samplingLevel':'HIGHER_PRECISION',}).execute(putToVar);
putToVar()
is a user defined function defined like so:
function putToVar(results)
{
//do processing with the results
}
It is my understanding that the .execute()
method is used to invoke a callback function for the asynchronous call gapi.client.analytics.data.ga.get()
. So I assume what function1().execute(function2)
does is call function2
with the return value from function1
as argument? Is this correct?
I'm in a situation where I need to apply several distinct filters and store them in an array to retrieve as and when required, irrespective of whether the API call returned a results object (it is an async call, so I don't know when the response comes, it is only visible to the callback function).
I would like to pass to the callback function the dimensions of the array in which to store the returned objects so that I can retrieve them on demand later, without worrying about the order in which the responses get processed. I say this because, initially I tried a for
loop and the order in which I got the response to my API calls were not the same as the order in which I placed API calls for my queries, so there were mismatches.
Since the reference uses this method to invoke the callback function, I would like to know how to pass additional arguments to a callback function like this when using .execute()
method, when I get to write putToVar()
function something like this:
function putToVar(results,arrayDim)
{
//Process Results
//Store in Array[arrayDim] the required value
}
I hope I have made myself clear. I have read the following posts
- 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?
but none of them seem to use the .execute()
method and I cannot figure out how to use what they have said. Or, if and how my .execute()
method (type of callback execution) can be modified to help my purpose.
Adding a closure would solve your problem:
The closure does the magic. It will allow to each loop cycle to have its own variables (not shared), so the proper ones will be inside
putToVar
when executed.I hope it's clear, if not, just let me know.
Just test it!
Cheers, from La Paz, Bolivia