Search code examples
javascriptcallbacknode.jstranslate

return value from a callback function in javascript?


I'm using node.js and the library Translate . Can i do something like this ? :


function traduce(text){
    translate.text(text,function(err,result){
        return result;
    });
}

And then use the result? It always return me "undefined". is there any way to use the result without do this? : .


translate.text(text,function(err,result){
     // use result
     // some logic
});


Solution

  • You aren't executing the function, you are passing a reference to an anonymous function. If you want the return value, execute it:

    function traduce(text){
        translate.text(text, (function(err,result){
            return result;
        })());
    }