从javascript中的回调函数返回值? [重复]

时间:2022-02-28 09:51:38

This question already has an answer here:

这个问题在这里已有答案:

I'm using node.js and the library Translate . Can i do something like this ? :

我正在使用node.js和库Translate。我可以这样做吗? :


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

3 个解决方案

#1


4  

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

#2


3  

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.

你能做到这一点并不是一个问题,但你应该这样做吗?这真的是理解异步代码的问题,node.js的每一个介绍都涵盖了一些深度。

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.

翻译本身使用谷歌API,所以向另一台服务器发出请求。如果你要等待结果,那将是一个冗长的阻塞操作,这是不可取的。

#3


-1  

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

他们提供30种语言的翻译。我认为,这意味着翻译是通过调用Web服务来完成的,对吧?也许node.js像其他语言一样提供类似“waitFor”的东西。但正如你所写,它是不可成功的

#1


4  

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

#2


3  

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.

你能做到这一点并不是一个问题,但你应该这样做吗?这真的是理解异步代码的问题,node.js的每一个介绍都涵盖了一些深度。

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.

翻译本身使用谷歌API,所以向另一台服务器发出请求。如果你要等待结果,那将是一个冗长的阻塞操作,这是不可取的。

#3


-1  

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

他们提供30种语言的翻译。我认为,这意味着翻译是通过调用Web服务来完成的,对吧?也许node.js像其他语言一样提供类似“waitFor”的东西。但正如你所写,它是不可成功的