Why "this" is pointing to something else in Javascript recursive function? - javascript

Consider the following JavaScript code which has a recursive boom function
function foo() {
this.arr = [1, 2, 3, 4, 5];
this.output = "";
this.get_something = function(n, callback) {
this.output += "(" + n + ")";
$.get("...", function(result) {
// do something with 'result'
callback();
});
};
this.boom = function() {
if (this.arr.length > 0) {
this.get_something(this.arr.shift(), this.boom);
}
};
this.boom();
document.write("output = [" + this.output + "]");
}
var f = new foo();
When get_something is executed for the first time and callback() is called, this.arr is not available anymore (probably because this is pointing to something else now).
How would you solve this ?

The problem is in Ajax requests and function call context
The problem you're having is function call context when boom gets called after you've received data from the server. Change your code to this and things should start working:
this.get_something = function(n, callback) {
var context = this;
this.output += "(" + n + ")";
$.get("...", function(result) {
// do something with 'result'
callback.call(context);
});
};
Additional suggestion
I know that your array has only few items but this code of yours is probably just an example and in reality has many of them. The problem is that your recursion will be as deep as your array has elements. This may become a problem because browsers (or better said Javascript engines in them) have a safety check of recursion depth and you will get an exception when you hit the limit.
But you will also have to change your document write and put it in the boom function since these calls are now no more recursive (it they were at all in the first place).
this.boom = function() {
if (this.arr.length > 0) {
this.get_something(this.arr.shift(), this.boom);
}
else {
document.write("output = [" + this.output + "]");
}
};
After some deeper observation
Your code actually doesn't execute in recursion unless you use synchronous Ajax requests which is by itself a show stopper and everyone would urge you to keep the async if at all possible. So basically my first solution with providing function call context would do the trick just fine.
If you're using async Ajax requests your document.write shouldn't display correct result, because it would be called too early. My last suggested boom function body would solve this issue as well.

this.get_something(this.arr.shift(), this.boom.bind(this));
Now you've bound this to be this. The context inside the boom function will always be what you expect it to be.
.bind is not supported in non-modern browsers so use the compatibility implementation.
As a side note $.proxy can do most of what .bind offers. So it may be simpler for you to use
this.get_something(this.arr.shift(), $.proxy(this.boom.bind, this));
.bind is currently supported by IE9, FF4 and Chrome.
.bind, jQuery.proxy

Related

How to resolve a promise with a parameter in setTimeout [duplicate]

I have some JavaScript code that looks like:
function statechangedPostQuestion()
{
//alert("statechangedPostQuestion");
if (xmlhttp.readyState==4)
{
var topicId = xmlhttp.responseText;
setTimeout("postinsql(topicId)",4000);
}
}
function postinsql(topicId)
{
//alert(topicId);
}
I get an error that topicId is not defined
Everything was working before I used the setTimeout() function.
I want my postinsql(topicId) function to be called after some time.
What should I do?
setTimeout(function() {
postinsql(topicId);
}, 4000)
You need to feed an anonymous function as a parameter instead of a string, the latter method shouldn't even work per the ECMAScript specification but browsers are just lenient. This is the proper solution, don't ever rely on passing a string as a 'function' when using setTimeout() or setInterval(), it's slower because it has to be evaluated and it just isn't right.
UPDATE:
As Hobblin said in his comments to the question, now you can pass arguments to the function inside setTimeout using Function.prototype.bind().
Example:
setTimeout(postinsql.bind(null, topicId), 4000);
In modern browsers (ie IE11 and beyond), the "setTimeout" receives a third parameter that is sent as parameter to the internal function at the end of the timer.
Example:
var hello = "Hello World";
setTimeout(alert, 1000, hello);
More details:
https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers.setTimeout
http://arguments.callee.info/2008/11/10/passing-arguments-to-settimeout-and-setinterval/
After doing some research and testing, the only correct implementation is:
setTimeout(yourFunctionReference, 4000, param1, param2, paramN);
setTimeout will pass all extra parameters to your function so they can be processed there.
The anonymous function can work for very basic stuff, but within instance of a object where you have to use "this", there is no way to make it work.
Any anonymous function will change "this" to point to window, so you will lose your object reference.
This is a very old question with an already "correct" answer but I thought I'd mention another approach that nobody has mentioned here. This is copied and pasted from the excellent underscore library:
_.delay = function(func, wait) {
var args = slice.call(arguments, 2);
return setTimeout(function(){ return func.apply(null, args); }, wait);
};
You can pass as many arguments as you'd like to the function called by setTimeout and as an added bonus (well, usually a bonus) the value of the arguments passed to your function are frozen when you call setTimeout, so if they change value at some point between when setTimeout() is called and when it times out, well... that's not so hideously frustrating anymore :)
Here's a fiddle where you can see what I mean.
I recently came across the unique situation of needing to use a setTimeout in a loop. Understanding this can help you understand how to pass parameters to setTimeout.
Method 1
Use forEach and Object.keys, as per Sukima's suggestion:
var testObject = {
prop1: 'test1',
prop2: 'test2',
prop3: 'test3'
};
Object.keys(testObject).forEach(function(propertyName, i) {
setTimeout(function() {
console.log(testObject[propertyName]);
}, i * 1000);
});
I recommend this method.
Method 2
Use bind:
var i = 0;
for (var propertyName in testObject) {
setTimeout(function(propertyName) {
console.log(testObject[propertyName]);
}.bind(this, propertyName), i++ * 1000);
}
JSFiddle: http://jsfiddle.net/MsBkW/
Method 3
Or if you can't use forEach or bind, use an IIFE:
var i = 0;
for (var propertyName in testObject) {
setTimeout((function(propertyName) {
return function() {
console.log(testObject[propertyName]);
};
})(propertyName), i++ * 1000);
}
Method 4
But if you don't care about IE < 10, then you could use Fabio's suggestion:
var i = 0;
for (var propertyName in testObject) {
setTimeout(function(propertyName) {
console.log(testObject[propertyName]);
}, i++ * 1000, propertyName);
}
Method 5 (ES6)
Use a block scoped variable:
let i = 0;
for (let propertyName in testObject) {
setTimeout(() => console.log(testObject[propertyName]), i++ * 1000);
}
Though I would still recommend using Object.keys with forEach in ES6.
Hobblin already commented this on the question, but it should be an answer really!
Using Function.prototype.bind() is the cleanest and most flexible way to do this (with the added bonus of being able to set the this context):
setTimeout(postinsql.bind(null, topicId), 4000);
For more information see these MDN links:
https://developer.mozilla.org/en/docs/DOM/window.setTimeout#highlighter_547041
https://developer.mozilla.org/en/docs/JavaScript/Reference/Global_Objects/Function/bind#With_setTimeout
You can pass the parameter to the setTimeout callback function as:
setTimeout(function, milliseconds, param1, param2, ...)
eg.
function myFunction() {
setTimeout(alertMsg, 3000, "Hello");
}
function alertMsg(message) {
alert(message)
}
Some answers are correct but convoluted.
I am answering this again, 4 years later, because I still run into overly complex code to solve exactly this question. There IS an elegant solution.
First of all, do not pass in a string as the first parameter when calling setTimeout because it effectively invokes a call to the slow "eval" function.
So how do we pass in a parameter to a timeout function? By using closure:
settopic=function(topicid){
setTimeout(function(){
//thanks to closure, topicid is visible here
postinsql(topicid);
},4000);
}
...
if (xhr.readyState==4){
settopic(xhr.responseText);
}
Some have suggested using anonymous function when calling the timeout function:
if (xhr.readyState==4){
setTimeout(function(){
settopic(xhr.responseText);
},4000);
}
The syntax works out. But by the time settopic is called, i.e. 4 seconds later, the XHR object may not be the same. Therefore it's important to pre-bind the variables.
I know its been 10 yrs since this question was asked, but still, if you have scrolled till here, i assume you're still facing some issue. The solution by Meder Omuraliev is the simplest one and may help most of us but for those who don't want to have any binding, here it is:
Use Param for setTimeout
setTimeout(function(p){
//p == param1
},3000,param1);
Use Immediately Invoked Function Expression(IIFE)
let param1 = 'demon';
setTimeout(function(p){
// p == 'demon'
},2000,(function(){
return param1;
})()
);
Solution to the question
function statechangedPostQuestion()
{
//alert("statechangedPostQuestion");
if (xmlhttp.readyState==4)
{
setTimeout(postinsql,4000,(function(){
return xmlhttp.responseText;
})());
}
}
function postinsql(topicId)
{
//alert(topicId);
}
Replace
setTimeout("postinsql(topicId)", 4000);
with
setTimeout("postinsql(" + topicId + ")", 4000);
or better still, replace the string expression with an anonymous function
setTimeout(function () { postinsql(topicId); }, 4000);
EDIT:
Brownstone's comment is incorrect, this will work as intended, as demonstrated by running this in the Firebug console
(function() {
function postinsql(id) {
console.log(id);
}
var topicId = 3
window.setTimeout("postinsql(" + topicId + ")",4000); // outputs 3 after 4 seconds
})();
Note that I'm in agreeance with others that you should avoid passing a string to setTimeout as this will call eval() on the string and instead pass a function.
My answer:
setTimeout((function(topicId) {
return function() {
postinsql(topicId);
};
})(topicId), 4000);
Explanation:
The anonymous function created returns another anonymous function. This function has access to the originally passed topicId, so it will not make an error. The first anonymous function is immediately called, passing in topicId, so the registered function with a delay has access to topicId at the time of calling, through closures.
OR
This basically converts to:
setTimeout(function() {
postinsql(topicId); // topicId inside higher scope (passed to returning function)
}, 4000);
EDIT: I saw the same answer, so look at his. But I didn't steal his answer! I just forgot to look. Read the explanation and see if it helps to understand the code.
The easiest cross browser solution for supporting parameters in setTimeout:
setTimeout(function() {
postinsql(topicId);
}, 4000)
If you don't mind not supporting IE 9 and lower:
setTimeout(postinsql, 4000, topicId);
https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout
I know it's old but I wanted to add my (preferred) flavour to this.
I think a pretty readable way to achieve this is to pass the topicId to a function, which in turn uses the argument to reference the topic ID internally. This value won't change even if topicId in the outside will be changed shortly after.
var topicId = xmlhttp.responseText;
var fDelayed = function(tid) {
return function() {
postinsql(tid);
};
}
setTimeout(fDelayed(topicId),4000);
or short:
var topicId = xmlhttp.responseText;
setTimeout(function(tid) {
return function() { postinsql(tid); };
}(topicId), 4000);
The answer by David Meister seems to take care of parameters that may change immediately after the call to setTimeout() but before the anonymous function is called. But it's too cumbersome and not very obvious. I discovered an elegant way of doing pretty much the same thing using IIFE (immediately inviked function expression).
In the example below, the currentList variable is passed to the IIFE, which saves it in its closure, until the delayed function is invoked. Even if the variable currentList changes immediately after the code shown, the setInterval() will do the right thing.
Without this IIFE technique, the setTimeout() function will definitely get called for each h2 element in the DOM, but all those calls will see only the text value of the last h2 element.
<script>
// Wait for the document to load.
$(document).ready(function() {
$("h2").each(function (index) {
currentList = $(this).text();
(function (param1, param2) {
setTimeout(function() {
$("span").text(param1 + ' : ' + param2 );
}, param1 * 1000);
})(index, currentList);
});
</script>
In general, if you need to pass a function as a callback with specific parameters, you can use higher order functions. This is pretty elegant with ES6:
const someFunction = (params) => () => {
//do whatever
};
setTimeout(someFunction(params), 1000);
Or if someFunction is first order:
setTimeout(() => someFunction(params), 1000);
Note that the reason topicId was "not defined" per the error message is that it existed as a local variable when the setTimeout was executed, but not when the delayed call to postinsql happened. Variable lifetime is especially important to pay attention to, especially when trying something like passing "this" as an object reference.
I heard that you can pass topicId as a third parameter to the setTimeout function. Not much detail is given but I got enough information to get it to work, and it's successful in Safari. I don't know what they mean about the "millisecond error" though. Check it out here:
http://www.howtocreate.co.uk/tutorials/javascript/timers
How i resolved this stage ?
just like that :
setTimeout((function(_deepFunction ,_deepData){
var _deepResultFunction = function _deepResultFunction(){
_deepFunction(_deepData);
};
return _deepResultFunction;
})(fromOuterFunction, fromOuterData ) , 1000 );
setTimeout wait a reference to a function, so i created it in a closure, which interprete my data and return a function with a good instance of my data !
Maybe you can improve this part :
_deepFunction(_deepData);
// change to something like :
_deepFunction.apply(contextFromParams , args);
I tested it on chrome, firefox and IE and it execute well, i don't know about performance but i needed it to be working.
a sample test :
myDelay_function = function(fn , params , ctxt , _time){
setTimeout((function(_deepFunction ,_deepData, _deepCtxt){
var _deepResultFunction = function _deepResultFunction(){
//_deepFunction(_deepData);
_deepFunction.call( _deepCtxt , _deepData);
};
return _deepResultFunction;
})(fn , params , ctxt)
, _time)
};
// the function to be used :
myFunc = function(param){ console.log(param + this.name) }
// note that we call this.name
// a context object :
myObjet = {
id : "myId" ,
name : "myName"
}
// setting a parmeter
myParamter = "I am the outer parameter : ";
//and now let's make the call :
myDelay_function(myFunc , myParamter , myObjet , 1000)
// this will produce this result on the console line :
// I am the outer parameter : myName
Maybe you can change the signature to make it more complient :
myNass_setTimeOut = function (fn , _time , params , ctxt ){
return setTimeout((function(_deepFunction ,_deepData, _deepCtxt){
var _deepResultFunction = function _deepResultFunction(){
//_deepFunction(_deepData);
_deepFunction.apply( _deepCtxt , _deepData);
};
return _deepResultFunction;
})(fn , params , ctxt)
, _time)
};
// and try again :
for(var i=0; i<10; i++){
myNass_setTimeOut(console.log ,1000 , [i] , console)
}
And finaly to answer the original question :
myNass_setTimeOut( postinsql, 4000, topicId );
Hope it can help !
ps : sorry but english it's not my mother tongue !
this works in all browsers (IE is an oddball)
setTimeout( (function(x) {
return function() {
postinsql(x);
};
})(topicId) , 4000);
if you want to pass variable as param lets try this
if requirement is function and var as parmas then try this
setTimeout((param1,param2) => {
alert(param1 + param2);
postinsql(topicId);
},2000,'msg1', 'msg2')
if requirement is only variables as a params then try this
setTimeout((param1,param2) => { alert(param1 + param2) },2000,'msg1', 'msg2')
You can try this with ES5 and ES6
setTimeout is part of the DOM defined by WHAT WG.
https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html
The method you want is:—
handle = self.setTimeout( handler [, timeout [, arguments... ] ] )
Schedules a timeout to run handler after timeout milliseconds. Any
arguments are passed straight through to the handler.
setTimeout(postinsql, 4000, topicId);
Apparently, extra arguments are supported in IE10. Alternatively, you can use setTimeout(postinsql.bind(null, topicId), 4000);, however passing extra arguments is simpler, and that's preferable.
Historical factoid: In days of VBScript, in JScript, setTimeout's third parameter was the language, as a string, defaulting to "JScript" but with the option to use "VBScript". https://learn.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/platform-apis/aa741500(v%3Dvs.85)
You can try default functionality of 'apply()' something like this, you can pass more number of arguments as your requirement in the array
function postinsql(topicId)
{
//alert(topicId);
}
setTimeout(
postinsql.apply(window,["mytopic"])
,500);
//Some function, with some arguments, that need to run with arguments
var a = function a(b, c, d, e){console.log(b, c, d, e);}
//Another function, where setTimeout using for function "a", this have the same arguments
var f = function f(b, c, d, e){ setTimeout(a.apply(this, arguments), 100);}
f(1,2,3,4); //run
//Another function, where setTimeout using for function "a", but some another arguments using, in different order
var g = function g(b, c, d, e){ setTimeout(function(d, c, b){a.apply(this, arguments);}, 100, d, c, b);}
g(1,2,3,4);
#Jiri Vetyska thanks for the post, but there is something wrong in your example.
I needed to pass the target which is hovered out (this) to a timed out function and I tried your approach. Tested in IE9 - does not work.
I also made some research and it appears that as pointed here the third parameter is the script language being used. No mention about additional parameters.
So, I followed #meder's answer and solved my issue with this code:
$('.targetItemClass').hover(ItemHoverIn, ItemHoverOut);
function ItemHoverIn() {
//some code here
}
function ItemHoverOut() {
var THIS = this;
setTimeout(
function () { ItemHoverOut_timeout(THIS); },
100
);
}
function ItemHoverOut_timeout(target) {
//do something with target which is hovered out
}
Hope, this is usefull for someone else.
As there is a problem with the third optonal parameter in IE and using closures prevents us from changing the variables (in a loop for example) and still achieving the desired result, I suggest the following solution.
We can try using recursion like this:
var i = 0;
var hellos = ["Hello World1!", "Hello World2!", "Hello World3!", "Hello World4!", "Hello World5!"];
if(hellos.length > 0) timeout();
function timeout() {
document.write('<p>' + hellos[i] + '<p>');
i++;
if (i < hellos.length)
setTimeout(timeout, 500);
}
We need to make sure that nothing else changes these variables and that we write a proper recursion condition to avoid infinite recursion.
// These are three very simple and concise answers:
function fun() {
console.log(this.prop1, this.prop2, this.prop3);
}
let obj = { prop1: 'one', prop2: 'two', prop3: 'three' };
let bound = fun.bind(obj);
setTimeout(bound, 3000);
// or
function funOut(par1, par2, par3) {
return function() {
console.log(par1, par2, par3);
}
};
setTimeout(funOut('one', 'two', 'three'), 5000);
// or
let funny = function(a, b, c) { console.log(a, b, c); };
setTimeout(funny, 2000, 'hello', 'worldly', 'people');
// These are three very simple and concise answers:
function fun() {
console.log(this.prop1, this.prop2, this.prop3);
}
let obj = { prop1: 'one', prop2: 'two', prop3: 'three' };
let bound = fun.bind(obj);
setTimeout(bound, 3000);
// or
function funOut(par1, par2, par3) {
return function() {
console.log(par1, par2, par3);
}
};
setTimeout(funOut('one', 'two', 'three'), 5000);
// or
let funny = function(a, b, c) { console.log(a, b, c); };
setTimeout(funny, 2000, 'hello', 'worldly', 'people');
I think you want:
setTimeout("postinsql(" + topicId + ")", 4000);
You have to remove quotes from your setTimeOut function call like this:
setTimeout(postinsql(topicId),4000);
Answering the question but by a simple addition function with 2 arguments.
var x = 3, y = 4;
setTimeout(function(arg1, arg2) {
return () => delayedSum(arg1, arg2);
}(x, y), 1000);
function delayedSum(param1, param2) {
alert(param1 + param2); // 7
}

Javascript Function logging to console from another function

I have a small problem, due to my lack of experiance with JS ...
I have a function in my file , which is logging to console correctly, but somehow, not returning same value it logged ( or maybe I do not know how to pull it ..)
function getStoragex() {
chrome.storage.sync.get('alertsOn', function(data) {
var optionShowAlertsx = data;
console.info("This is logging ok" + optionShowAlertsx.alertsOn);
return optionShowAlertsx.alertsOn;
});
}
The logging is :
DATA true
Later on, I have this ( inside another function
)
var optionShowAlerts = getStoragex();
console.info("This is logging undefined " + optionShowAlerts);
What am I doing wrong ??
Your return statement is inside the anonymous function you're passing to chrome.storage.sync.get. Your getStoragex function never issues a return and so a call to it gets the result undefined.
If chrome.storage.sync.get is a synchronous function (which it seems like it might be from the name), you can do this:
function getStoragex() {
var rv;
chrome.storage.sync.get('alertsOn', function(data) {
var optionShowAlertsx = data;
console.info("This is logging ok" + optionShowAlertsx.alertsOn);
rv = optionShowAlertsx.alertsOn;
});
return rv;
}
(That bracing style is unfamiliar to me, apologies if I've messed it up.)
Edit: It looks to me as though the sync in that name doesn't have to do with the function being synchronous or asynchronous, but rather with data syncing.
If it's asynchonous, then you can't return the result from getStoragex because getStoragex returns before the result is available. In that case, you can accept a callback that you, um, call back with the result when you have it:
function getStoragex(callback) {
chrome.storage.sync.get('alertsOn', function(data) {
var optionShowAlertsx = data;
console.info("This is logging ok" + optionShowAlertsx.alertsOn);
callback(optionShowAlertsx.alertsOn);
});
}
Alternately, promises are gaining a lot of popularity at the moment. You might look into using one of those (there are several implementations available). The result will still be asynchronous if chrome.storage.sync.get is asynchronous, though.
Your return statement return value to it chrome.storage.sync.get method 2nd parameter itself. it will not return to getStoragex() method.
try this
function getStoragex() {
var optionShowAlertsx;
chrome.storage.sync.get('alertsOn', function(data) {
optionShowAlertsx = data;
console.info("This is logging ok" + optionShowAlertsx.alertsOn);
});
return optionShowAlertsx.alertsOn
}
var optionShowAlerts = getStoragex();
console.log("This is logging undefined " + optionShowAlerts);

JavaScript Asynch Callback - How to await the endresult

I have the following situation (see also jsFiddle -> http://jsfiddle.net/sMuWK/):
function CallBackStringHandler() {
this.callback = function(){return null};
};
CallBackStringHandler.prototype.doTheMagic = function(callback) {
var result = callback.call(this);
if(result == null)
alert("Nothing to handle yet...");
else
alert("End the result is: \n\n" + result);
};
function Action(){
var result = null;
var max = 10;
var index = 0;
var processor = setInterval(function(){
if(index <= max){ //Processing step
if(result == null)
result = "" + index;
else
result += index;
index++;
} else { //Done
clearInterval(processor);
alert(result);
}
},10);
return result;
};
function Run(){
var handler = new CallBackStringHandler();
handler.doTheMagic(Action);
};
Run();
A script (a jQuery plugin) allows you to specify a callback that has to return a string.
This string will be handled by this script.
So far so good.
For the sake of performance and keeping my page responsive, I want to build this string in a multi-threaded way. Since this is not a web standard yet, I simulate this with the help of setInterval.
Now I know that the essence of doing things this way is not waiting for the results.
But I can't think of a way of keeping things responsive and fast and return the full result to the handler.
So the end result (in this example) should show: 012345678910.
Any help/clues would be appreciated.
Cheers, another nerd.
You need to turn it the other way around. Action is not a callback, it does not consume an asynchronous result but it produces it. doTheMagic on the other hand is the callback, as it consumes the result (by alerting the result).
Thus, instead of passing Action as a "callback" to doTheMagic, you should be passing doTheMagic as a callback to Action.
function Run() {
var handler = new CallBackStringHandler();
Action(function(result) {
handler.doTheMagic(result);
});
// or, alternatively: (only in modern browsers supporting Function.bind)
Action(handler.doTheMagic.bind(handler));
};
Make Action accept a callback argument and call it when it's done. Finally, let doTheMagic just receive the result. I forked your fiddle, have a look!
Note: You won't get multi-threading using setInterval, it will still run in the same browser thread as the rest of your script. If you truly need to do some serious heavy lifting, you may want to use a web worker.
For most cases such as just concatenating a string like you're doing, this is overkill. Workers live in a completely separate environment and you can only communicate with them through messages, which adds quite a bit of complexity to your application. Make sure to do a good amount of testing and benchmarking before deciding that you really need a multi-threaded approach!
So to for a final answer I kinda resolved it this way (fork here):
function CallBackStringHandlerBy3rdParty() {};
CallBackStringHandlerBy3rdParty.prototype.doMagic = function(callback) {
var result = callback.call(this);
alert(result);
};
CallBackStringHandlerBy3rdParty.prototype.doMyOwnMagic = function(result) {
if(result.isComplete) {
this.doMagic(function(){return result.value;});
} else {
var that = this;
result.value += 1;
if(result.value < 10)
setTimeout(function(){that.doMyOwnMagic(result);},10);
else {
result.isComplete = true;
this.doMyOwnMagic(result);
}
}
};
function Run(){
var handler = new CallBackStringHandlerBy3rdParty();
var result = {};
result.value = 0;
result.isComplete = false;
handler.doMyOwnMagic(result);
};
Run();
Cheers!

Use same variable that is defined in another function

This may seem simple to some but I am less experienced with JavaScript. I have two functions. One is called when my upload begins. The next is called when my upload ends.
In the first function, a variable is created, a unique id used for the upload. What is the best way to go about reusing it in my second function since it is not global? The reason I defined it within my function is because every time a user clicks the upload button, the function is called and a NEW id is created for that upload, that is why I do not want to define it outside because then the same id would be served for a second upload unless the page is refreshed.
Anyone got any suggestions?
function uploadstart() {
function makeid() {
var text = "";
var possible = "abcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < 32; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
var rand_id = makeid();
}
uploadfinish(){
//rand_id will be undefined
}
Pass in that var as a parameter
uploadstart(){
function makeid()
{
var text = "";
var possible = "abcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < 32; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
var rand_id=makeid();
//Pass in rad_id
uploadfinish(rand_id);
}
uploadfinish(radomID){
//rand_id will be undefined
}
Try declaring rand_id in global scope (before everything)
var rand_id;
function bla....
The solution to this problem depends on how and where you use those two functions. If you pass them as callbacks to another function from some ajax library, or something like that, and if you control that library call, you could use a closure.
So, if for example you do something like this when an upload is begun:
Library.foo(..., uploadstart, uploadfinish);
You could define makeID as a global function, and then bind the generated id to your callbacks using a function like this:
function bind_id(rand_id, my_function) {
return function() { // return a closure
return my_function(); // my_function is executed in a context where rand_id is defined
}
}
Then you define your callbacks using rand_id as if it were global (actually, it will defined in the closure):
function uploadstart() {
// use rand_id as you wish
}
function uploadend() {
// use rand_id as you wish
}
When you need to call your Library.foo function, first generate the rand_id, then bind it to the start and end callbacks:
var new_rand_id = randID();
Library.foo(..., bind_id(new_rand_id,uploadstart), bind_id(new_rand_id,uploadend));
This way you'll pass to foo not the original uploadstart and uploadend, but two closures where rand_id is defined and i the same for both, so that callback code can use that variable.
PS: closures are one of the most powerful and trickiest features of javascript. If you're serious about the language, take your time to study them well.
What do you do with the rand_id once you've created it? Could you not just call uploadfinish with the rand_id as a parameter?
function makeid()
{
...
}
var rand_id=makeid();
uploadfinish(rand_id);
}
uploadfinish(id){
//rand_id will be 'id'
}
[EDIT] Since you said you need to call the function externally, check out this page for details about callbacks:Create custom callbacks
function doSomething(callback) {
// ...
// Call the callback
callback('stuff', 'goes', 'here');
}
function foo(a, b, c) {
// I'm the callback
alert(a + " " + b + " " + c);
}
doSomething(foo);
That will call doSomething, which will call foo, which will alert
"stuff goes here".
Note that it's very important to pass the function reference doSomething(foo),
rather than calling the function and passing its result like this: doSomething(foo()).

Javascript: Nested Callbacks/MySQL Results

I am sure this is a basic question, but I have been searching google for awhile and can't find a satisfactory answer..
I am used to programming MySQL select queries in PHP and simply grabbing a result, looping through each row, and within the loop doing further queries based on the column values of each individual row.
However, I'm working with javascript server side code now that relies on a SQL object where you pass the query and then a callback function that will be invoked after the query is run.
I'm confused with some of the scoping issues and how to best cleanly do this. For example, I don't want to do something like:
SQL.query("select * from blah", function(result) {
for(var i = 0; i < result.length; i++) {
SQL.query("select * from blah2 where i =" + result[i].property, function(result2) {
//now how do I access result from here? I know this isn't scoped correctly
});
}
});
What is the standard way to write this style of nested SQL query and not have scoping issues/messy code? Thanks!
This is very interesting... I've never heard of "server-side javascript"... but none the less this might help organize your code a bit. I use this method to organize my ajax request callbacks.
using your example it would look like this.
SQL.query("select * from some_table", function(result){ runNestedQuery(result); });
function runNestedQuery(result){
for(var i = 0; i < result.length; i++) {
SQL.query("select * from blah2 where i =" + result[i].property, function(result2){ nestedResult(result2); });
}
}
There are no scoping issues with your above code - but this is a nice way I like to organize this kind of thing.
result will be available in the second callback, that's how closures in JavaScript work, the functions has access to all variables in the outer scopes it was defined in.
function outer() {
var foo = 1;
function inner() { // inherits the scope of outer
var bla = 2;
console.log(foo); // works!
// another function in here well inherit both the scope of inner AND outer, and so on
}
inner();
console.log(bla); // doesn't work, raises "ReferenceError: bla is not defined"
}
outer();
Now, on to the problem, i will not point to the correct value, it too will be inherited to the second callback but it`s a reference and will therefore has the wrong value.
Fix is to create another closure:
SQL.query("select * from blah", function(result) {
for(var i = 0; i < result.length; i++) {
(function(innerResult) { // anonymous function to provide yet another scope
SQL.query("select * from blah2 where i =" + innerResult.property, function(result2) {
// innerResult has the correct value
});
})(result[i]); // pass the current result into the function
}
});
Or an extra function:
function resultThingy(result) {
SQL.query("select * from blah2 where i =" + result.property, function(result2) {
// result has the correct value
});
}
SQL.query("select * from blah", function(result) {
for(var i = 0; i < result.length; i++) {
resultThingy(result[i]);
}
});
Since you are using server-side Javascript, you can likely use forEach. Assuming that result instanceof Array == true:
SQL.query("select * from blah", function(result) {
result.forEach(function(item, index) {
SQL.query("select * from blah2 where i = " + item.property, function(result2) {
console.log(item, index, result); //works as intended
});
});
});
If result is merely array-like, then this
Array.prototype.forEach.call(result, function(item, index) { // etc...
should do the trick.
As others have pointed out result actually will be available all the way down in the nested callback.
But there is a very tricky part to this:
...Because the nested query runs asynchronously, your code will actually fire off a bunch of parallel queries -- one for each row in result -- all running at the same time (!). This is almost certainly not what you want; and unless result is very small indeed, all the simultaneous queries will use up all your available db connections rather quickly.
To remedy this, you might use something like this:
SQL.query("select * from blah", function(result) {
handleBlahRow( result, 0 );
});
function handleBlahRow( result, i ) {
if( !result || (i >= result.length)) return;
SQL.query("select * from blah2 where i =" + result[i].property, function(result2) {
// kick off the next query
handleBlahRow( result, i+1 );
// result, i, *and* result2 are all accessible here.
// do whatever you need to do with them
});
});
The above will run your nested queries 1-at-a-time. It's fairly easy to adapt the above to introduce limited parallelism (eg. 4-at-a-time), if you want it -- though it's probably not necessary.

Categories

Resources