javascript 中回调函数的返回值?
我正在使用 node.js 和库 翻译 。我可以做这样的事情吗? :
function traduce(text){
translate.text(text,function(err,result){
return result;
});
}
然后使用结果?它总是返回“未定义”。有没有办法在不这样做的情况下使用结果? : 。
translate.text(text,function(err,result){
// use result
// some logic
});
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
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您没有执行该函数,而是传递对匿名函数的引用。如果想要返回值,执行:
You aren't executing the function, you are passing a reference to an anonymous function. If you want the return value, execute it:
问题不在于你能不能那样做,而在于你是否应该那样做。这实际上是一个理解异步代码的问题,每一篇 Node.js 的介绍都会深入地介绍这一点。
Translate 本身使用 google api,因此向另一台服务器发出请求。如果您等待结果,这将是一个漫长的阻塞操作,这是不可取的。
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.
他们提供 30 种语言的翻译。我想,这意味着翻译是通过调用网络服务来完成的,对吧?也许node.js 提供了类似“waitFor”的东西,就像其他一些语言一样。但正如你所写,这是无法完成的
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