带有 node-cmd 的 Node JS:等到先前的 cmd 调用执行完成

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

我想在我的 Node JS 应用程序中通过 node-cmd 调用一系列 python 脚本。它们相互依赖,所以我不能并行执行它们。我也不能使用固定的等待时间,因为它们总是有不同的执行时间。现在,在调用我的代码时,所有脚本都被同时调用,因此出现错误...请参阅我的代码:

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);
});
},

您知道如何不并行执行这些脚本的解决方案吗?

你可以Promisify回调风格的函数,然后使用.then一个接一个地执行。像这样

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));

node-cmd 自述文件中也提到了它。看这里 - https://www.npmjs.com/package/node-cmd#with-promises

根据文档,您可以承诺 cmd.get

.then 的替代 await 下面

// 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()
}