如何解决动态创建的承诺清单?

编程入门 行业动态 更新时间:2024-10-10 19:18:16

<a href=https://www.elefans.com/category/jswz/34/1771394.html style=如何解决动态创建的承诺清单?"/>

如何解决动态创建的承诺清单?

我正在编写一个git pre-commit钩子,我希望能够向它传递一个要执行的命令数组,以便它执行它们,如果失败则抛出错误。这些命令的示例可能是运行测试套件或构建。

我在使用Node的child_process exec命令的约定版本动态地执行此操作时遇到问题。

到目前为止,我有一个带有2个示例命令的配置文件:

config.js

const config = {
  onPreCommit: ['git --version', 'node -v'],
};

module.exports = config;

如果我使用此代码手动传递值,则可以像我期望的那样从命令中获得使用正确值实现的promise对象:

预提交挂钩

function preCommit() {
  if (config.onPreCommit && config.onPreCommit.length > 0) {
    Promise.allSettled([
      exec(config.onPreCommit[0]),
      exec(config.onPreCommit[1]),
    ]).then((results) => results.forEach((result) => console.log(result)));
  }
}

preCommit();

但是,如果我尝试像下面这样动态地执行此操作,则会引发错误:

function preCommit() {
  if (config.onPreCommit && config.onPreCommit.length > 0) {
    const cmdPromises = config.onPreCommit.map((cmd, i) => {
      return new Promise((resolve, reject) => {
        exec(cmd[i])
          .then((res) => {
            resolve(res);
          })
          .catch((err) => {
            reject(err);
          });
      });
    });

    Promise.allSettled(cmdPromises).then((results) =>
      results.forEach((result) => console.log(result))
    );
  }
}

preCommit();

被拒绝的承诺:

Error: Command failed: o 'o' is not recognized as an internal or external command, operable program or batch file.

Error: Command failed: o
  'o' is not recognized as an internal or external command,
  operable program or batch file.
回答如下:

由于comment by mtkopone,问题出在我的地图功能中。

通过将exec(cmd[i])更改为exec(cmd)固定

还更新了功能,因此钩子可以正常工作:

function preCommit() {
  if (config.onPreCommit && config.onPreCommit.length > 0) {
    // Loop through scripts passed in and return a promise that resolves when they're done
    const cmdPromises = config.onPreCommit.map((cmd) => {
      return new Promise((resolve, reject) => {
        exec(cmd)
          .then((res) => {
            resolve(res);
          })
          .catch((err) => {
            reject(err);
          });
      });
    });

    // Make sure all scripts been run, fail with error if any promises rejected
    Promise.allSettled(cmdPromises)
      .then((results) =>
        results.forEach((result) => {
          if (result.status === 'rejected') {
            console.log(result.reason);
            process.exit(1);
          }
        })
      )
      .then(() => {
        // If no errors, exit with no errors - commit continues
        process.exit(0);
      });
  }
}

preCommit();

更多推荐

如何解决动态创建的承诺清单?

本文发布于:2024-05-07 15:35:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1756943.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何解决   清单   动态

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!