1
exports.getDefiniton = function (text) {
    var definition = "";

    wn.definitions(text, {
        useCanonical: true
        , includeRelated: true
        , limit: 3
    }, function (e, defs) {
        definition = defs[0].word + ': 1.' + defs[0].text;
        definition += '\n2.' + defs[1].text;
        definition += '\n3.' + defs[2].text;
        console.log(definition)
    });
    return definition;
};

Console.log inside function(e, defs) works.

but the return statement doesn't seem to return the value.

How to properly return 'definition' variable?

N-Alpr
  • 336
  • 2
  • 11
Xuva
  • 21
  • 6
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Jeremy Thille Oct 24 '17 at 12:14
  • learn about callback concept https://www.tutorialspoint.com/nodejs/nodejs_callbacks_concept.htm – Idemax Oct 24 '17 at 12:24

1 Answers1

1

since wn.definition is an Asynchronous call you should use promise or async/await or callback features.

Using callback your code would be like something like this (for example lets say you store this in a def.js file):

exports.getDefiniton = function (text, callback) {
    var definition = "";

    wn.definitions(text, {
        useCanonical: true
        , includeRelated: true
        , limit: 3
    }, function (e, defs) {
        definition = defs[0].word + ': 1.' + defs[0].text;
        definition += '\n2.' + defs[1].text;
        definition += '\n3.' + defs[2].text;
        console.log(definition);
        callback(definition);
    });
};

and you can use def.js module like this:

var defModule = require("./def");

defModule.getDefiniton("Hello", function (defintion) {
    console.log(defintion);
});

UPDATE: @Xuva in that case check the code below:

var defModule = require("./def");

defModule.getDefiniton("Hello", function (definition) {
    displayMessage(text, definition);
    //rest of the code ...
});
N-Alpr
  • 336
  • 2
  • 11
  • But the problem is that in main program, I'm using something like `displayMessage(text, defModule.getDefiniton(text))` – Xuva Oct 24 '17 at 12:29
  • Do something like `let res = await defModule.getDefinition(text); displayMessage(text, res);` – user835611 Oct 24 '17 at 12:33
  • @Xuva check the update part. but I recommend you to use promise and async/await since they are much more cleaner ... but it is critical to understand the asyn nature of the node.js – N-Alpr Oct 24 '17 at 12:36