2

I am trying to write a function that takes a word and returns an array with all the synonyms found from natural nodes wordnet lookup function (https://github.com/NaturalNode/natural)

However, I am having problems returning the final array. I think my problem is something to do with scopes. As if i log the array within the wordnet lookup, I have the correct array. However, this doesnt seem to effect the array I am trying to return

var getSynomyns = function(keyword){
    var synonymsArr = [];
    console.log(`GETTING SYNOMYNS FOR ${keyword}`);

    wordnet.lookup(keyword, function(results){
        results.forEach(function(result){
            result.synonyms.forEach(function(syn){
                if(synonymsArr.indexOf(syn) === -1){
                    synonymsArr.push(syn);
                }
            });
        });
    console.log(synonymsArr);
    //return synonyms;
    });
    return synonymsArr;
}

As an example, if I put the work 'test' into the fucntion I would like it to return all the synonyms of 'test' However, it just reutrns an empty array.

Let me know if that is not clear and thanks for the help :)

EDIT: I see this is a common question, however, the tagged duplicate is not clear in answering this for me. if someone could explain with my code that would be appricated.

Callum Clark
  • 79
  • 1
  • 7
  • That's a very common question in NodeJS, since it is event based. You can look for a duplicate here https://stackoverflow.com/questions/25399725/nodejs-get-async-return-value-callback – drinchev Dec 11 '18 at 10:24
  • Possible duplicate of [NodeJS get async return value (callback)](https://stackoverflow.com/questions/25399725/nodejs-get-async-return-value-callback) – drinchev Dec 11 '18 at 10:24
  • 1
    The tagged responses are not clear as to how I can solve this. could someone explain with my code block to make it clearer? – Callum Clark Dec 11 '18 at 10:59
  • `wordnet.lookup` is an async function – drinchev Dec 11 '18 at 11:01

0 Answers0