Search code examples
javascriptpythonnode.jscallbackwait

Node JS with node-cmd: wait until execution of prior cmd call is finished


I have a series of python scripts that I want to call via node-cmd in my Node JS application. They rely on each other, so I cannot execute them in parallel. I also cannot use a fixed waiting time, as they always have different execution time. Right now, upon call of my code, all scripts are called at the same time and therefore error... see my code:

pythoncaller: function(req, callback) {

var cmd=require('node-cmd');

cmd.get(`python3 first.py`,
    function(err, data, stderr){
      console.log(err);
      console.log(stderr);
      console.log(data);
});
cmd.get(`python3 second.py`,
    function(err, data, stderr){
      console.log(err);
      console.log(stderr);
      console.log(data);
});

cmd.get(`python3 third.py"`,
    function(err, data, stderr){
      console.log(err);
      console.log(stderr);
      console.log(data);

});
cmd.get(`python3 last.py"`,
    function(err, data, stderr){
      console.log(err);
      console.log(stderr);
      console.log(data);
      callback(data);
});
},

Do you know a solution on how to execute those scripts not in parallel?


Solution

  • You can Promisify the callback style functions and use .then to execute them one after another. something like this

    const cmd = require('node-cmd');
    const Promise = require("bluebird");
    const getAsync = Promise.promisify(cmd.get, { multiArgs: true, context: cmd });
    
    var cmd = require('node-cmd');
    
    getAsync(`python3 first.py`)
      .then(data => console.log(data))
      .then(() => getAsync(`python3 second.py`)
      .then(data => console.log(data))
      .then(() => getAsync(`python3 third.py"`)
      .then(data => console.log(data))
      .then(() => getAsync(`python3 last.py"`)
      .then(data => console.log(data));
    
    

    It is also mentioned on node-cmd readme. See here - https://www.npmjs.com/package/node-cmd#with-promises