1

I'm new to node js,

I call my python script from node, and I want to wait until the python script over. what is the simplest way? my code :

    PythonShell.run('public/python/dag.py', null, function (err,result) {
        if (err) throw err;
        console.log(result)
       
      })        
      
      console.log("amit")

my output:

"amit"
["hey python"]

expected output:

["hey python"]
"amit"
amit
  • 71
  • 2
  • 10
  • 1
    You're missing the basics of async JS. See https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call – Estus Flask Dec 05 '21 at 10:18

1 Answers1

0

You see this output because node executes tasks asynchronously.

What you could instead do is have a function that returns a Promise containing the python part and await that function before you go to the next part.

Something like this should work:

function runpythoncode(){
  return new Promise(resolve => {
    PythonShell.run('public/python/dag.py', null, function (err,result) {
      if (err) throw err;
      console.log(result);
      resolve();
    })
  })
}
 
await runpythoncode();

console.log('amit')
segfault
  • 46
  • 3