Pattastisch
Pattastisch

Reputation: 21

call nodejs and python asynchronously

everybody,

i want to call a python script asynchronously in my node script. I use "python-shell" for this.

My problem is that node executes its own code first and then the python script. I need the python script data during runtime.

That means :

let {PythonShell} = require('python-shell');
let message;

PythonShell.run('python.py',null,function(err,res){
if(err) throw err;
message =res;
console.log("1",res);
}
console.log("2",{message});

Output: => 2 undefined => 1 foo

I need the result but like this: => 1 foo => 2 foo

Can you help me by writing me a little example? i already read that it might work with .on and .end but i don't understand how !

Upvotes: 1

Views: 524

Answers (1)

Ashish Modi
Ashish Modi

Reputation: 7770

The reason is because your run method is asynchronous and callback based. That means it will fire the method and move forward to the next statement. In this case it is your console statement printing 2 and message. Since you are setting message inside the callback, it is executed after the console statement and hence you are seeing this behavior. To fix this you need to move your console statement inside the callback like this

const {PythonShell} = require("python-shell");
let message;

PythonShell.run("python.py", null, function (err, res) {
  if (err) {
    throw err;
  }
  message = res;
  console.log("1", res);
  console.log("2", {message});
});

Upvotes: 2

Related Questions