Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return value from a callback function in javascript? [duplicate]

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

like image 762
Daniel Flores Avatar asked Feb 19 '11 21:02

Daniel Flores


2 Answers

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;
    })());
}
like image 118
Eli Avatar answered Oct 11 '22 23:10

Eli


It's not so much a question can you do that, but should you do that. It's really a matter of understanding asynchronous code, something which every introduction to node.js covers in some depth.

Translate itself uses the google api, so makes a request to another server. If you were to wait for the result it would be a lengthy blocking operation, which is undesirable.

like image 40
leebriggs Avatar answered Oct 11 '22 22:10

leebriggs