Saturday, October 19, 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

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...