0

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?

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

According to doc, you may promisify cmd.get.

Alternative to .then with await below

// copy pasted
// either Promise = require('bluebird') or use (require('util').promisify)
const getAsync = Promise.promisify(cmd.get, { multiArgs: true, context: cmd })

pythoncaller: async function(req, callback) {
  try {
    let data
    data = await getAsync(`python3 first.py`)
    data = await getAsync(`python3 second.py`)
    data = await getAsync(`python3 third.py"`)
    // ...
  } catch (e) {
    return callback(e)
  }
  return callback()
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.