简体   繁体   English

从双重嵌套函数返回值

[英]returning value from double-nested function

i am trying to get a simple value from my node server like so: 我正在尝试从我的节点服务器中获取一个简单的值,如下所示:

getNodeServerValue = function()      {
    return io.socket.emit('server-Query', 
         function(data) {
               console.log('data is now: ' + data);  // works fine!
               return (data);
         }
   );
}

and i wish to be able retrieve the value like this: 我希望能够像这样检索值:

var myReturnedValue = getNodeServerValue();

but returnedValue contains the function itself, and not the value being returned. 但是returnValue包含函数本身,而不包含返回的值。 and getNodeServerValue()() did not work either. 和getNodeServerValue()()也不起作用。

i have attempted returning a variable, setTimeout, clearTimeout, etc. with no success because of the async nature of jScript. 由于jScript的异步特性,我尝试返回变量,setTimeout,clearTimeout等均未成功。

this example is loosely based on the "Sending and getting data (acknowledgements" example in the socket.io docs. 该示例大致基于socket.io文档中的“发送和获取数据(确认)”示例

looking here and here didn't help me since my requirements are double nested, and also i need to name the getNodeServerValue with a variable. 这里这里查找并没有帮助我,因为我的需求是双重嵌套的,而且我还需要用变量命名getNodeServerValue

i am sure this is an easy question, so please dont down-vote me without an explanation. 我确信这是一个简单的问题,所以请不要在没有任何解释的情况下对我投下反对票。

thank you very much. 非常感谢你。

You can use a promise library, or if in Node they are supported natively 您可以使用Promise库,或者如果在Node中它们本身受支持

io.getNodeServerValue = new Promise(function (resolve, reject) {
  io.socket.emit('server-Query', 
         function(data) {
               resolve(data);
         }
   );
});

use it like so: 像这样使用它:

io.getNodeServerValue.then(function (data) {
  // data is here!
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM