Saturday 19 October 2019

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

});


Answer



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

}

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...