I'm making this really simple application to help me explore nodejs and I have a particular handler that generates HTML code based on the top10 messages in my database. The snippet I'm having problem with loops through the messages and call the function generating HTML and appends the result to my html string.
function CreateMessageboard(BoardMessages){
var htmlMessageboardString = "";
[... Console debug code ...]
for(var i = 0; i < BoardMessages.length;i++){
(function(){
var j = i;
console.log("Loading message %d".green, j);
htmlMessageboardString += MessageToHTMLString(BoardMessages[j]);
})();
}
}
I think my problem is due to either Javascript's way of handling loops, related to closures from what I read and this is what I tried using above or the async way nodejs handles my function. Right now the 10 results are well returned from the db but the last message is processed at every loop.
I also tried, instead of doing var j = i, to take value i as function parameter and pass it in the closure and it returned the same results anyway.
I have a feeling I'm missing critical knowledge to solve my problem, can I get light on this matter ?
Edit : I'm welcome to give any other info on the code, I'd post the whole git repo but people probably don't want to swim through a whole project to help me debug this issue so I posted the whole function in the comments to provide more context.
i. Is that your exact code?function(i){......})(i);so that there's no doubtiis captured.MessageToHTMLString(BoardMessages[messageNumber])in a temporary variable and output that, before concatenating. After those changes, can you post the code and console output again?