I have a table in a database which has a list of bad_words
and 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