【问题标题】:How to run two child processes in succession in node JS如何在节点JS中连续运行两个子进程
【发布时间】:2020-09-06 22:55:56
【问题描述】:

我有两个过程,一个是从音频生成一个 json 文件,另一个是规范化 json 文件,它们都在一个函数中。

每次我运行函数,第一个运行,第二个拒绝运行,当第二个运行时,第一个拒绝运行。

我希望能够在第一个之后运行第二个。

exec(command, (error, stdout, stderr) => {
    if (error) {
      console.log("Normalize error", error);
      return;
    }
    if(stderr){
      console.log(`stderr: ${stderr}`);
      return
    } 
    console.log(`stdout: ${stdout}`);
  });

上面的代码是生成音频文件的代码

 exec(`python3 py/scale-json.py json/${song.filename}/.json`, (error, stdout, stderr) => {
        console.log("I AM EXECUTING", song.filename)
        if (error) {
        console.log("Python error", error);
        }
        console.log(`stdout-python: ${stderr}`);
    })

虽然上面的代码对其进行了规范化。

我如何一个接一个地运行它们?

【问题讨论】:

  • 你为什么打电话给resolve()reject()?是否有一个包含承诺执行器功能的地方定义了这些?如果是这样,请也显示该代码。或者你只是突然打电话给那些?
  • 您遇到了什么错误?而且,尝试一个接一个地运行这些的代码在哪里?
  • 有一个包含承诺,但是,我已经更新了它

标签: javascript node.js exec child-process


【解决方案1】:

您是否尝试过使用 Normalizer 作为回调部分?

 exec(`python3 py/scale-json.py json/${song.filename}/.json`, (error, stdout, stderr) => {
        console.log("I AM EXECUTING", song.filename)
        if (error) {
            throw new Error (error);
        }
        console.log(`stdout-python: ${stderr}`);

        // It goes here!
        exec(command, (error, stdout, stderr) => {
            if (error) {
                console.log("Normalize error", error);
                return;
            }
            if(stderr){
                console.log(`stderr: ${stderr}`);
                reject("error");
                return;
            } 
            resolve("complete")
            console.log(`stdout: ${stdout}`);
        });
    })

【讨论】:

  • 我会试试这个
  • 好的!如果有帮助,请告诉我!
【解决方案2】:

我会承诺 exec() 函数,然后使用基于承诺的逻辑对它们进行排序:

const util = require('util');
const exec = util.promisify(require('child_process').exec);

async function run() {
    const { stdout: stdout1, stderr: stderr1 } = await exec(command);

    // some logic based on stdout1 or stderr1
    
    const { stdout: stdout2, stderr: stderr2 } = await exec(python3 py/scale-json.py json/${song.filename}/.json`);

    // process final results here
    return something;
}

// Call it like this:
run().then(result => {
    console.log(result);
}).catch(err => {
    console.log(err);
});

您可以了解util.promisify() 如何与child_process.exec() here in the doc 协同工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-13
    • 1970-01-01
    • 1970-01-01
    • 2022-11-01
    • 2017-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多