如何解决动态创建的承诺清单?"/>
如何解决动态创建的承诺清单?
我正在编写一个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();
更多推荐
如何解决动态创建的承诺清单?
发布评论