Node js - 同步执行Websocket的对象函数

Node js - Synchronous execution of Websocket's object functions

我有以下类似的功能

//Have to connect to a websocket
var websocket = new WebSocket(wsUri);
var channel = new WebChannel(websocket);

The webchannel returns an object that has list of functions

//The following functions
actualTest1Value = 1;
actualTest2Value = 2;
objectReturned = channel.object.objectReturned
test1= objectReturned.getValueFor("Sample");
test2 = objectReturned.getValueFor("Sample1");
if(test1 === actualTest1Value && test2 === actualTest2Value)
{
  //do some Operation
}

这里的问题是,由于 node js 的异步特性,test1 和 test 2 未定义。由于该对象是从服务器返回的,因此我无法向该对象的功能添加承诺。有什么方法可以同步执行吗?

我做了一个小的解决方法来一个接一个地执行。

test1 = objectReturned.getValueFor("Sample", function(returnVal){
test1 = returnVal;
compare();
});
test2 = objectReturned.getValueFor("Sample1", function(returnVal){
test2 = returnVal;
compare();
});

After this wrap the comparison in a separate function

function compare()
{
   //before doing this check test2 is not undefined, because both values will be 
   //defined on second callback.
   if(test1 === actualTest1Value && test2 === actualTest2Value)
   {
        //do some Operation
   }
}

我很幸运能够将 test1 和 test2 作为全局变量,并在每个函数的回调上调用函数 compare() 并仅当回调来自第二个函数时才比较两个值对我有帮助。