0

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?

sbrk
  • 1,338
  • 1
  • 17
  • 25
  • you need to understand how to use asynchronous code – Jaromanda X Oct 20 '16 at 05:41
  • I know I need a callback function of some sort, I don't know how to implement it exactly. – sbrk Oct 20 '16 at 05:42
  • sorry, but when you say `How do I return only after forEach has finished executing?` that doesn't seem like you know you need a callback function - that seems like you want to return after the asynchronous functions have finished – Jaromanda X Oct 20 '16 at 05:44

0 Answers0