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
});
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;
})());
}
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.
They are providing translations of 30 languages. I think, that means that the translation is made by calling a webservice, right? Maybe node.js provides something like "waitFor" like in some other languages. But as you ve written it is not accomplishable
精彩评论