Cannot assign value to variable by reference in Javascript

154 views Asked by At

I would like to assign value to the variable IMLoginReq inside a ProtoBuf load function, but its not working, can anyone help?

var IMLoginReq;
protobuf.load("./pb/IM.Login.proto", (err, root) => {
    // Obtain a message type
    IMLoginReq = root.lookup("IM.Login.IMLoginReq");
    console.log(IMLoginReq);//<== is not undefined
});
console.log(IMLoginReq);//<== is undefined
2

There are 2 answers

2
Taplar On BEST ANSWER

The load() method is asynchronous. As such the console.log at the end will happen before the load finishes. Instead of trying to treat this as procedural logic, which it is not, you should instead use the IMLoginReq inside the success method that you have.

1
Flak On

Thats because you are trying to call it before its loaded. You should have a callback function like success so it will be there. You can also use promises by omitting the callback:

protobuf.load("awesome.proto")
    .then(function(root) {
       ...
    });