Xuva
Xuva

Reputation: 21

Unable to return value from node js module

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?

Upvotes: 1

Views: 84

Answers (1)

N-Alpr
N-Alpr

Reputation: 336

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 ...
});

Upvotes: 1

Related Questions