开发者

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

This question already has an answer here: How can we return string from callback function to root function in node.js? (1 answer) Closed 7 years ago.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜