Node.Js - 连续命令后退出exec

Node.Js - exit out of exec after continuous commands

我正在按顺序执行一些 git 命令,特别是,我正在遵循 git 流程模型,

例如完成功能时,我 运行,

git pull
git push -u origin branchname
git pull origin develop
git checkout develop
git merge branchname
git push

我 运行 这些命令使用 node.js 中的 exec 模块,我将它们一个接一个地链接起来,例如:

exec(command1,
     (err, stdout, stderr) => {
            if(err != null) {
                  //display an error message
                  return
            } else {
                  exec(command2, (err, stdout, stderr) =>{ ... }
            }

      }
)

等等。输出工作正常,订单有效。但是,如果其中一个命令失败,我将脱离链条。

我知道根据 ,我可以使用一个异步库来达到相同的效果。但是,这是不求助于第三方库的最佳方法吗?其他人是怎么做到的?

使用 async 你可以用 eachSeries:

var commands = [
  'git pull',
  'git checkout',
  '...'
];

eachSeries(commands, (command, cb) => {
  exec(command, (err, stdout, stderr) => {
    cb(err);
  });
});

通常来说,找到一个执行此操作的库比手动解决您自己的解决方案要好。

However, is this the best possible way to do that without resorting to a third-party library?

没有

How have other people done it?

还有其他三种解法:

  • 只需使用该库即可。被使用是它的全部目的。
  • 重新发明那个图书馆。因为那样它就不再是第三方了,不管它有什么好处。
  • 使用承诺! (和部分应用)

    function makeExec(command) {
        return function(/* ignore results */) {
            return new Promise(function(resolve, reject) {
                child_process.exec(command, function(err, stdout, stderr) {
                    if (err != null) reject(Object.assign(err, {stderr}));
                    else resolve(stdout);
                });
            });
        });
    }
    Promise.resolve()
    .then(makeExec("git pull"))
    .then(makeExec("git push -u origin branchname"))
    .then(makeExec("git pull origin develop"))
    .then(makeExec("git checkout develop"))
    .then(makeExec("git merge branchname"))
    .then(makeExec("git push"))
    .catch(function(err) {
        //display an error message
    })