Saturday 25 February 2017

Javascript: How do I ensure something happens only after forEach loop finishes?

I have a table in a database which has a list of bad_wordsand a list of good_words which replace these bad_words in the input string. This is how I'm doing it, the parameter comment is to be tested for the bad_words and replaced by the corresponding good_words.




function testComment(comment) {
var words = comment.split(" ");
var resultString = "";
words.forEach(function(word){
connection.query('select good_words from words where bad_words = ' + connection.escape(word), function(err, result){
if(err){
console.log(err);
return;
}
if(result.length != 0){

resultString = comment.replace(word, result[0].good_words));
}
});
});
return resultString;
}


However, this just returns the empty string (the original initialized value). This is because the function returns before the forEach finishes. How do I ensure
1) I'm modifying the resultString and not creating a new instance inside the forEach loop? Do I need to use this.resultString = ... instead?
2) How do I return only after forEach has finished executing?

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...