Using Javascript closure to pass additional data to an API callback function - javascript

I have gotten this to work a bit but can't seem to figure out what the exact phrasing to get the for loop to pass the correct value will be.
for(i=0; i < the_stores.length; i++) {
uid = the_stores[i].id;
// get the lat long and write info to the console
geocoder.getLatLng(the_stores[i].address, function(point) { return callbackFunc(point, uid); });
}
function callbackFunc(point, myID) {
if(point !== null) {
console.log(point.toString());
console.log(myID);
} else {
return false;
}
}
I'm using the Google Maps API, v2. I want that for loop to pass in a different value of uid to the callback function for each iteration through the loop, but right now it passes in the same value every time. Anyone know how to get the desired effect here? I feel like I'm pretty close. Thank you!

What you are looking for is an "Immediately Invoked Function Expression". Since JavaScript only has function scope, not block scope, all references to uid are being bound to the same variable.
(For more, see: http://benalman.com/news/2010/11/immediately-invoked-function-expression/)
Here's a simple way to do it:
for(i=0; i < the_stores.length; i++) {
(function() {
var uid = the_stores[i].id;
// get the lat long and write info to the console
geocoder.getLatLng(the_stores[i].address, function(point) { return callbackFunc(point, uid); });
})();
}

Use your callbackFunc to return a handler that references the values that need to be retained.
for(i=0; i < the_stores.length; i++) {
// get the lat long and write info to the console
geocoder.getLatLng(the_stores[i].address, callbackFunc(the_stores[i].id));
}
function callbackFunc(myID) {
return function(point) {
if(point !== null) {
console.log(point.toString());
console.log(myID);
} else {
return false;
}
};
}

This is why I like Array.forEach() so much. It takes care of all these kind of common problems with loops for you. Use it like this:
the_stores.forEach(function (store, i) {
geocoder.getLatLng(store.address, function(point) {
return callbackFunc(point, store.id);
});
}
Array.forEach() is native JavaScript in modern browsers, but for IE8 and IE7 you need to add it yourself. I recommend using the implementation provided by MDN. In my humble opinion, a JS5 shim that includes at least all the new Array methods should be boiler plate for any website.

Related

function with function argument

I just wondering to find a keyword or a solution so that I can further find and fix my own problem, so basically, I wanted to call a function but from a function argument, like this.
var arg = function() {/*do something*/};
function do(arg) {
arg();
}
do(arg);
But I want to put multiple functions on it, but not constant, it sometimes can be 1 function, or sometimes 2 functions or more, is there any solution that I can take? or a keyword to I start searching with? I already searched the internet but I could not find what I want.
You could use some really cool new feature called rest parameters. Here is an example.
function callMultiple(...fn) {
fn.forEach(fn => fn());
}
function FnOne() {
console.log('function one called');
}
function FnTwo() {
console.log('function two called');
}
callMultiple(FnOne, FnTwo);
Now callMultiple can take any number of functions.
MDN reference
function doFn(){
for(var i = 0; i < arguments.length; i++) arguments[i]();
}
One line ES6:
var doFn = (...args) => args.forEach(fn => fn());
PD: ´do´ is a reserved word, you should use diffetent variable name.
What you need to do to your do() function is this:
function do(args) {
for (var i = 1; i <= args.length; i += 1) {
args[i]();
}
}
This would fix your problem. However, you should know that do is a JavaScript keyword, so you should avoid using it as a variable or function of your own.
EDIT: You must include anything you're passing to your function, so you need to add the args parameter.

Javascript Function Scoped For Loops

Here's an example of a situation where a simple JS loop does not behave as expected, because of the loop variable not being in a separate scope.
The solution often presented is to construct an unpleasant-looking bit of loop code that looks like this:
for (var i in obj) {
(function() {
... obj[i] ...
// this new shadowed i here is now no longer getting changed by for loop
})(i);
}
My question is, could this be improved upon? Could I use this:
Object.prototype.each = function (f) {
for (var i in this) {
f(i,this[i]);
}
};
// leading to this somewhat more straightforward invocation
obj.each(
function(i,v) {
... v ...
// alternatively, v is identical to
... obj[i] ...
}
);
when I ascertain that I need a "scoped loop"? It is somewhat cleaner looking and should have similar performance to the regular for-loop (since it uses it the same way).
Update: It seems that doing things with Object.prototype is a huge no-no because it breaks pretty much everything.
Here is a less intrusive implementation:
function each (obj,f) {
for (var i in obj) {
f(i,obj[i]);
}
}
The invocation changes very slightly to
each(obj,
function(i,v) {
... v ...
}
);
So I guess I've answered my own question, if jQuery does it this way, can't really go wrong. Any issues I've overlooked though would warrant an answer.
Your answer pretty much covers it, but I think a change in your original loop is worth noting as it makes it reasonable to use a normal for loop when the each() function isn't handy, for whatever reason.
Update: Changed to use an example that's similar to the example referenced by the question to compare the different approaches. The example had to be adjusted because the each() function requires a populated array to iterate over.
Assuming the following setup:
var vals = ['a', 'b', 'c', 'd'],
max = vals.length,
closures = [],
i;
Using the example from the question, the original loop ends up creating 2n functions (where n is the number of iterations) because two functions are created during each iteration:
for (i = 0; i < max; i++) {
closures[i] = (function(idx, val) { // 1st - factoryFn - captures the values as arguments
return function() { // 2nd - alertFn - uses the arguments instead
alert(idx + ' -> ' + val); // of the variables
};
})(i, vals[i]);
}
This can be reduced to creating only n + 1 functions by creating the factory function once, before the loop is started, and then reusing it:
var factoryFn = function(idx, val) {
return function() {
alert(idx + ' -> ' + val);
};
};
for (i = 0; i < max; i++) {
closures[i] = factoryFn(i, vals[i]);
}
This is nearly equivalent to how the each() function might be used in this situation, which would also result in a total of n + 1 functions created. The factory function is created once and passed immediately as an argument to each().
each(vals, function(idx, val) {
closures[idx] = function() {
alert(idx + ' -> ' + val);
};
});
FWIW, I think a benefit to using each() is the code is a bit shorter and creating the factory function right as it's passed into the each() function clearly illustrates this is its only use. A benefit of the for loop version, IMO, is the code that does the loop is right there so it's nature and behavior is completely transparent while the each() function might be defined in a different file, written by someone else, etc.
Global Scope
When something is global means that it is accessible from anywhere in your code. Take this for example:
var monkey = "Gorilla";
function greetVisitor () {
return alert("Hello dear blog reader!");
}
If that code was being run in a web browser, the function scope would be window, thus making it
available to everything running in that web browser window.
Local Scope
As opposed to the global scope, the local scope is when something is just defined and accessible in a
certain part of the code, like a function. For instance;
function talkDirty () {
var saying = "Oh, you little VB lover, you";
return alert(saying);
}
alert(saying); // Throws an error
If you take a look at the code above, the variable saying is only available within the talkDirty
function. Outside of it it isn’t defined at all. Note of caution: if you were to declare saying without
the var keyword preceding it, it would automatically become a global variable.
What this also means is that if you have nested functions, the inner function will have access to the
containing functions variables and functions:
function saveName (firstName) {
function capitalizeName () {
return firstName.toUpperCase();
}
var capitalized = capitalizeName();
return capitalized;
}
alert(saveName("Robert")); // Returns "ROBERT"
As you just saw, the inner function capitalizeName didn’t need any parameter sent in, but had complete
access to the parameter firstName in the outer saveName function. For clarity, let’s take another
example:
function siblings () {
var siblings = ["John", "Liza", "Peter"];
function siblingCount () {
var siblingsLength = siblings.length;
return siblingsLength;
}
function joinSiblingNames () {
return "I have " + siblingCount() + " siblings:\n\n" + siblings.join("\n");
}
return joinSiblingNames();
}
alert(siblings()); // Outputs "I have 3 siblings: John Liza Peter"
As you just saw, both inner functions have access to the siblings array in the containing function, and
each inner function have access to the other inner functions on the same level (in this case,
joinSiblingNames can access siblingCount). However, the variable siblingsLength in the siblingCount is
only available within that function, i.e. that scope.

How to pass Array/Values to a Javascript function

I am learning Javascript for a project using online resources however i don't know how to get this function working.
var results =[[a1,a2,a3,a4,a5]];
var winner = 0;
function checkWinner (results)
{
for (var i = 0; i < results.length; i++)
if (results[0][i] > 50)
{
winner = results[0][i];
}
}
Just after the function, i use:
checkWinner(results);
In a HTML file i use alert to display the variable winner. But it obviously doesn't work. I realise it is a problem with my understanding of scope and global variables.
should be
var Results =[[a1,a2,a3,a4,a5]];
var winner = 0;
function checkWinner (results)
{
for (var i = 0; i < results[0].length; i++)
if (results[0][i] > 50)
{
winner = results[0][i];
}
}
checkWinner(Results);
To avoid name collisions name global variables from capital case.
Also in your code you call the length of the "parent" array. You need to specify the length of the "Child" array
You've got to understand the concept of scope. The variables results and winner are not the same inside and outside the function.
Also, you've got to call the function and return something from it if you want to change the value of the variables outside the function (unless you use globals). This seems to be hard for novice programmers to understand, but merely defining a function doesn't do anything.
var results =[[a1,a2,a3,a4,a5]];
function checkWinner (results)
{
for (var result in results[0])
{
if (result > 50)
{
return result;
}
}
}
var winner = checkWinner(results);
Note that:
I used a for each loop, which has a cleaner syntax.
I am also iterating over results[0] instead of results, since you've got a nested array for whatever reason.
Because your function has an argument called results, it requires you to pass the global results in spite of it being a global. Another way to do this:
var results = [[a1,a2,a3,a4,a5]];
function checkWinner()
{
for (var result in results[0])
{
if (result > 50)
{
winner = result;
return;
}
}
}
checkWinner();
However, I would recommend against using global variables this way. Here's an explanation on why global variables are bad. It's for C++, but it applies to JavaScript as well.
You're iterating over the result[0] array (the array in result[0]), but using the length of the result array.

Defining and calling function in one step

Is there a way in Javascript to define a function and immediately call it, in a way that allows it to be reused?
I know you can do one-off anonymous functions:
(function(i) {
var product = i * i;
console.log(product);
// Can't recurse here because there's no (ECMA standard) way for the
// function to refer to itself
}(2)); // logs 4
Or you can name a function then call it afterwards:
function powers(i) {
var product = i * i;
console.log(i * i);
if (product < 1e6) { powers(product) };
}
powers(2); // Logs 4, 16, 256...
But is there a cleaner way of defining and calling a function in one go? Sort of like a hybrid of both examples?
Not being able to do this isn't preventing me from doing anything, but it feels like it would be a nice expressive way to write recursive functions or functions that need to be run on $(document).ready() but also later when situations change, etc.
You can try:
(window.powers = function(i) {
/*Code here*/
alert('test : ' + i);
})(2);
Click
Working link : http://jsfiddle.net/SqBp8/
It gets called on load, and I have added it to an anchor tag to change the parameter and alert.
If all you want is access the function within its own body, you can simply specify a name after the function keyword:
> (function fac (n) {
return (n === 0 ? 1 : n*fac(n-1));
})(10)
3628800
This is a standard feature (see ECMA-262, ed. 5.1, p. 98).
All the answers here are close to what you want, but have a few problems (adding it to the global scope, not actually calling it, etc). This combines a few examples on this page (although it unfortunately requires you to remember arguments.callee):
var test = (function() {
alert('hi');
return arguments.callee;
})();
Later, you can call it:
test();
If you don't care about the return value, you can do this.
var powers = function powers(i) {
var product = i * i;
console.log(i * i);
if (product < 1e6) { powers(product) };
return powers;
}(2);

Javascript - synchronizing after asynchronous calls

I have a Javascript object that requires 2 calls out to an external server to build its contents and do anything meaningful. The object is built such that instantiating an instance of it will automatically make these 2 calls. The 2 calls share a common callback function that operates on the returned data and then calls another method. The problem is that the next method should not be called until both methods return. Here is the code as I have implemented it currently:
foo.bar.Object = function() {
this.currentCallbacks = 0;
this.expectedCallbacks = 2;
this.function1 = function() {
// do stuff
var me = this;
foo.bar.sendRequest(new RequestObject, function(resp) {
me.commonCallback(resp);
});
};
this.function2 = function() {
// do stuff
var me = this;
foo.bar.sendRequest(new RequestObject, function(resp) {
me.commonCallback(resp);
});
};
this.commonCallback = function(resp) {
this.currentCallbacks++;
// do stuff
if (this.currentCallbacks == this.expectedCallbacks) {
// call new method
}
};
this.function1();
this.function2();
}
As you can see, I am forcing the object to continue after both calls have returned using a simple counter to validate they have both returned. This works but seems like a really poor implementation. I have only worked with Javascript for a few weeks now and am wondering if there is a better method for doing the same thing that I have yet to stumble upon.
Thanks for any and all help.
Unless you're willing to serialize the AJAX there is no other way that I can think of to do what you're proposing. That being said, I think what you have is fairly good, but you might want to clean up the structure a bit to not litter the object you're creating with initialization data.
Here is a function that might help you:
function gate(fn, number_of_calls_before_opening) {
return function() {
arguments.callee._call_count = (arguments.callee._call_count || 0) + 1;
if (arguments.callee._call_count >= number_of_calls_before_opening)
fn.apply(null, arguments);
};
}
This function is what's known as a higher-order function - a function that takes functions as arguments. This particular function returns a function that calls the passed function when it has been called number_of_calls_before_opening times. For example:
var f = gate(function(arg) { alert(arg); }, 2);
f('hello');
f('world'); // An alert will popup for this call.
You could make use of this as your callback method:
foo.bar = function() {
var callback = gate(this.method, 2);
sendAjax(new Request(), callback);
sendAjax(new Request(), callback);
}
The second callback, whichever it is will ensure that method is called. But this leads to another problem: the gate function calls the passed function without any context, meaning this will refer to the global object, not the object that you are constructing. There are several ways to get around this: You can either close-over this by aliasing it to me or self. Or you can create another higher order function that does just that.
Here's what the first case would look like:
foo.bar = function() {
var me = this;
var callback = gate(function(a,b,c) { me.method(a,b,c); }, 2);
sendAjax(new Request(), callback);
sendAjax(new Request(), callback);
}
In the latter case, the other higher order function would be something like the following:
function bind_context(context, fn) {
return function() {
return fn.apply(context, arguments);
};
}
This function returns a function that calls the passed function in the passed context. An example of it would be as follows:
var obj = {};
var func = function(name) { this.name = name; };
var method = bind_context(obj, func);
method('Your Name!');
alert(obj.name); // Your Name!
To put it in perspective, your code would look as follows:
foo.bar = function() {
var callback = gate(bind_context(this, this.method), 2);
sendAjax(new Request(), callback);
sendAjax(new Request(), callback);
}
In any case, once you've made these refactorings you will have cleared up the object being constructed of all its members that are only needed for initialization.
I can add that Underscore.js has a nice little helper for this:
Creates a version of the function that will only be run after first
being called count times. Useful for grouping asynchronous responses,
where you want to be sure that all the async calls have finished,
before proceeding.
_.after(count, function)
The code for _after (as-of version 1.5.0):
_.after = function(times, func) {
return function() {
if (--times < 1) {
return func.apply(this, arguments);
}
};
};
The license info (as-of version 1.5.0)
There is barely another way than to have this counter. Another option would be to use an object {} and add a key for every request and remove it if finished. This way you would know immediately which has returned. But the solution stays the same.
You can change the code a little bit. If it is like in your example that you only need to call another function inside of commonCallback (I called it otherFunction) than you don't need the commonCallback. In order to save the context you did use closures already. Instead of
foo.bar.sendRequest(new RequestObject, function(resp) {
me.commonCallback(resp);
});
you could do it this way
foo.bar.sendRequest(new RequestObject, function(resp) {
--me.expectedCallbacks || me.otherFunction(resp);
});
That's some good stuff Mr. Kyle.
To put it a bit simpler, I usually use a Start and a Done function.
-The Start function takes a list of functions that will be executed.
-The Done function gets called by the callbacks of your functions that you passed to the start method.
-Additionally, you can pass a function, or list of functions to the done method that will be executed when the last callback completes.
The declarations look like this.
var PendingRequests = 0;
function Start(Requests) {
PendingRequests = Requests.length;
for (var i = 0; i < Requests.length; i++)
Requests[i]();
};
//Called when async responses complete.
function Done(CompletedEvents) {
PendingRequests--;
if (PendingRequests == 0) {
for (var i = 0; i < CompletedEvents.length; i++)
CompletedEvents[i]();
}
}
Here's a simple example using the google maps api.
//Variables
var originAddress = "*Some address/zip code here*"; //Location A
var formattedAddress; //Formatted address of Location B
var distance; //Distance between A and B
var location; //Location B
//This is the start function above. Passing an array of two functions defined below.
Start(new Array(GetPlaceDetails, GetDistances));
//This function makes a request to get detailed information on a place.
//Then callsback with the **GetPlaceDetailsComplete** function
function GetPlaceDetails() {
var request = {
reference: location.reference //Google maps reference id
};
var PlacesService = new google.maps.places.PlacesService(Map);
PlacesService.getDetails(request, GetPlaceDetailsComplete);
}
function GetPlaceDetailsComplete(place, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
formattedAddress = place.formatted_address;
Done(new Array(PrintDetails));
}
}
function GetDistances() {
distService = new google.maps.DistanceMatrixService();
distService.getDistanceMatrix(
{
origins: originAddress,
destinations: [location.geometry.location], //Location contains lat and lng
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.IMPERIAL,
avoidHighways: false,
avoidTolls: false
}, GetDistancesComplete);
}
function GetDistancesComplete(results, status) {
if (status == google.maps.DistanceMatrixStatus.OK) {
distance = results[0].distance.text;
Done(new Array(PrintDetails));
}
}
function PrintDetails() {
alert(*Whatever you feel like printing.*);
}
So in a nutshell, what we're doing here is
-Passing an array of functions to the Start function
-The Start function calls the functions in the array and sets the number of PendingRequests
-In the callbacks for our pending requests, we call the Done function
-The Done function takes an array of functions
-The Done function decrements the PendingRequests counter
-If their are no more pending requests, we call the functions passed to the Done function
That's a simple, but practicle example of sychronizing web calls. I tried to use an example of something that's widely used, so I went with the Google maps api. I hope someone finds this useful.
Another way would be to have a sync point thanks to a timer. It is not beautiful, but it has the advantage of not having to add the call to the next function inside the callback.
Here the function execute_jobs is the entry point. it take a list of data to execute simultaneously. It first sets the number of jobs to wait to the size of the list. Then it set a timer to test for the end condition (the number falling down to 0). And finally it sends a job for each data. Each job decrease the number of awaited jobs by one.
It would look like something like that:
var g_numJobs = 0;
function async_task(data) {
//
// ... execute the task on the data ...
//
// Decrease the number of jobs left to execute.
--g_numJobs;
}
function execute_jobs(list) {
// Set the number of jobs we want to wait for.
g_numJobs = list.length;
// Set the timer (test every 50ms).
var timer = setInterval(function() {
if(g_numJobs == 0) {
clearInterval(timer);
do_next_action();
}
}, 50);
// Send the jobs.
for(var i = 0; i < list.length; ++i) {
async_task(list[i]));
}
}
To improve this code you can do a Job and JobList classes. The Job would execute a callback and decrease the number of pending jobs, while the JobList would aggregate the timer and call the callback to the next action once the jobs are finished.
I shared the same frustration. As I chained more asynchronous calls, it became a callback hell. So, I came up with my own solution. I'm sure there are similar solutions out there, but I wanted to create something very simple and easy to use. Asynq is a script that I wrote to chain asynchronous tasks. So to run f2 after f1, you can do:
asynq.run(f1, f2)
You can chain as many functions as you want. You can also specify parameters or run a series of tasks on elements in an array too. I hope this library can solve your issues or similar issues others are having.

Categories