I am new to Javascript, I am confused about the code below for hours.
I wanna know why i can't assign the value of result to htmlContent.
Thanks!
var htmlContent = fs.readFileSync(program.file);
restler.get('http://google.com').on('complete', function(result) {
if (result instanceof Error) {
util.puts('Error: ' + result.message);
} else {
htmlContent = result;
}
});
console.log(htmlContent);
The problem here is that the line starting with restler.get begins before the console.log, but it doesn't finish before it necessarily.
You should put your console.log inside the restler.get call.
I would look up the concept of futures and promises in JS, this might help clear up some fundamentals:
http://monochrome.sutic.nu/2012/04/06/javascript-futures.html
When you are using continuations in JS (a requirement in node.js especially), you really need to get your head around them.
Here, your function inside the .on() will be called asynchronously (in simple words it will get executed when "complete" event occurs i.e. some later time) and you are using console.log(htmlContent) is regular function call, so you can not set htmlContent value inside the function this way.
If you want to use result value in any other function then you should pass this value to your next function. I hope this will work.
Related
I'm learning javascript programming.
My js code works.
But one problem is that the below code simplified to ask send big data to server Almost simultaneously.
I want to send data one by one.
How to fix it by using closure ? :-)
$("#dataupload").click(function(){
for (var i = 0 ; i < datafiles.length; i++) {
var f = datafiles[i] ;
$.post("/upload.php",f,function(result){
console.log(result);
});
}
});
If you want to do it serially, you can do something like this:
(function send(i) {
if(i < datafiles.length) {
$.post("/upload.php", datafiles[i], function(result) {
console.log(result);
send(++i);
});
}
})(0);
Here send is a function that is part of an immediately-invoked function-expression. We're replicating a loop here by using the callback. Although we are calling send here it is important to note that this isn't strictly recursive, since the subsequent call to send is note done while send itself is executing, but is called when the callback of $.post is executed.
send takes one argument, which is an index into your datafiles array. If i is lesser than the length of the array, it means that we still have files to send. We make a call to $.post, and in the callback, we increment the value of i and call send again with the new value of i. When i becomes equal to the length of the datafiles array, it means that we are done.
If I console.log the output from count+1, I get a correct number value. If I output the value of note.note_id, I get undefined. Why is this?
I have tried setting value to a predefined one inside the function.
note.note_id = db.notes.count(function(err, count) {
return count + 1;
});
Hard to answer without knowing what db.notes is but it seems to be something accessing a database. This means it's most likely asynchronous which meansa that the count() method will never return a value but you need to do whatever you want to do with the result inside the callback.
db.notes.count(function(err, count) {
note.note_id = count + 1;
// do more stuff here
});
// do NOT do stuff here. it will run BEFORE the callback has been executed
var k=0;var n=0;
function shiftrigh(){
n=n+1;
if(n<=193)
window.setTimeout(shiftright(),100);
else
n=0;}
function shiftright(){
k-=1;
document.getElementById("abcmngcontainer").style.left=k+"px";
window.setTimeout(shiftrigh(),100);
}
function shiftlef(){
n=n+1;
if(n<=193)
window.setTimeout(shiftleft(),100);
else
n=0;}
function shiftleft(){
k+=1;
document.getElementById("abcmngcontainer").style.left=k+"px";
window.setTimeout(shiftlef(),100);
}
Hi, I have the above code. The function shiftrigh when called invokes shiftright and then a cycle
is created then goes on until n is 193. Same is the case for the shiflef pair.
The code is working but it is working pretty quick. Whether I decrease the time value in settimeout or increase it, it remains the same. The updates are pretty quick, not smooth enough to see.
Change:
window.setTimeout(shiftright(),100);
to:
window.setTimeout(shiftright,100);
Note the missing parens. The same with shiftleft() -> shiftleft.
This is a common misunderstanding in JavaScript. setTimeout() requires a reference to a function (shiftright). What you are doing is calling that function immediately and passing whatever was returned from it to setTimeout(). Clearly not what was intended.
You are using window.setTimeout wrong!
window.setTimeout(shiftlef(),100);
You have to pass a function reference, not the return code of the function.
So the right version looks like this:
window.setTimeout(shiftlef,100);
setTimeout will need a function-NAME or a function-"variable"/"pointer" as first argument...
in your code, you pass the RETURN value of your function-call as first parameter to "setTimeout"....
just remove the braces ->
window.setTimeout(shiftleft, 100)
Neither this nor that works. Does anyone know what is going on??
Edit:
qwerty is simply called as "qwerty();" when in other pieces of code.
It is supposed to be indepedent.
Edit: I realize what is wrong. The problem lies with the i...
function qwerty () {
..... for loop that changes i ......
var that = this;
this.chara[i] = createlabel.....
this.chara[i].addEventListener('click', function(e) {
var j = e.source.id;
alert("hello word");
alert(this.chara[j].width); // I get the error here
});
this.chara[i].addEventListener('doubleclick', function(e) {
alert("hello word");
alert(that.chara[i].width); // I get the error here too.
});
}
Any JS problem relating to this is likely due to the way the function using this is called. Storing a reference to this in your that variable should let you reference it from within your nested functions, exactly the way you are doing it already - assuming that qwerty() is called in a way that sets this to the correct object in the first place. (Personally I like to call such a variable self since it more accurately reflects what the variable is doing.)
However, in your function you say you get the error on this line:
that.chara[i].width
Given that you say this.chara[i].addEventListener(...) I'm guessing that the chara[i] variable holds a reference to a DOM element. If that is the case I'm guessing it is an element type that doesn't have a width property. Try this:
that.chara[i].style.width
https://developer.mozilla.org/en/CSS/width
That's the best I can do for you without more information about what error you're getting and how the qwerty() function is called...
How could I find in jQuery what events are bound with live for a particular element?
Say I have a function, randomFunction, that returns a random function from an array of functions. How can I find which function has been bound to a certain element?
var arrayOfFunctions = []; //a whole bunch of functions
function randomFunction(array){}; //returns one of those functions
$('#certain_element').live('click', randomFunction(arrayOfFunctions));
What is the index of the array that corresponds to the function that was bound by live for $('#certain_element')?
Alright, figured it out.
For a click event, for $('#certain_element'), logging each binding's index to the console:
var relevantHandlers = $.map($(document).data('events').live, function(value){
if(value.origType == 'click' && value.selector == '#certain_element'){
return value.handler;
}
}; //all handlers for #certain_element bound to click by live.
$.each(relevantHandlers, function(){
console.log("the index is: " + $.inArray(this, arrayOfFunctions));
});
Take a look at this plugin. When I last used this, there was a need to slightly modify it for the then latest version of jQuery, but it should give you a direction.
There's a nifty bookmarklet called Visual Event that shows the code that will be called.
But since you're truly calling a random function, maybe doing something as simple as including an alert("function name") or colsone.log("function"), if you're just testing.