How to invoke Python connection sequentially in Javascript:Node.js

354 Views Asked by At

I'm trying to develop a connection between node.js file and Python code which I achieved successfully using zeroRPC. The problem arises when I try to run the node.js file, after executing each line of node.js file, in the end it executes the 'invoke' command that makes the python connection and calls the python function and retrieves the value.For example:

Node.js File:

  var global_variable = 0;
  var json_object = "Some Json Object";
  console.log("1");
  NodeToPython(json_object);         //Calling the function

  function NodeToPython(json_object_local)
  {
     var send_json = json_object_local;
     var zerorpc = require("zerorpc");
     var client = new zerorpc.Client();
     client.connect("tcp://localhost:4242");

     console.log("2");
     client.invoke("receive", send_json, function(error, res, more) 
     {
       global_variable = JSON.parse(res);        // 'res' stores retrieved value from Python code
       console.log("3");
       client.close();
     }
     console.log("4");
 }
 console.log("5");

Python File:

   import zerorpc, json
   class XYZ(object):

      def receive(self,response):                    // Called function 
          self.response=json.loads(response);
          print("Py");
          return json.dumps(self.response,encoding="utf-8",indent=2);

The output of the above code will be as follows: 1 2 4 5 Py 3

I want the output to be sequential like line by line and should simultaneously call and get the value from Python function also, like this: 1 2 Py 3 4 5

1

There are 1 best solutions below

2
On

NodeJS favors continuation passing style of programming. When you call invoke on the client, you are scheduling a function to run later. Whenever the RPC call succeeded or failed this function will be called with the result and possible error. From then you can continue work and schedule more function.