0

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

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

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

4

2 回答 2

1

您可以 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

于 2020-01-21T09:16:12.170 回答
0

根据 doc,您可以承诺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()
}
于 2020-01-21T09:27:46.833 回答