I have the following like functionality
//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
}
The problem here is, the test1 and test 2 is undefined because of the asynchronous nature of node js. As the object is returned from a server, I cannot add a promise to the functions of the object. Is there any way to execute this synchronously?
I did a small workaround to execute one after the other.
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
}
}
I was lucky to have test1 and test2 as global variables and calling the function compare() on the callback of each functions and comparing both values only when the callback comes from second one helped me.