【发布时间】:2021-01-27 10:39:26
【问题描述】:
我有一个数组中的命令列表,我需要按顺序运行:
const commands = [
`git clone https://github.com/EliLillyCo/${repo}.git`,
`cd ${repo}`, `git checkout -b ${branch}`,
'cp ../codeql-analysis.yml .github/workflows/',
'git add .github/workflows/codeql-analysis.yml',
`git push --set-upstream origin ${branch}`,
'cd ../',
`rm -r ${repo}`,
];
它们需要按顺序运行,因为命令依赖于正在运行的前一个命令。
另外,每个命令在运行下一个命令之前需要等待 3 秒,因为有时命令需要时间,尤其是命令 1 和命令 5。
我正在使用标准的 for 循环,然后使用 setTimeout() 调用函数来运行命令,如下所示:
const a = require('debug')('worker:sucess');
const b = require('debug')('worker:error');
const { exec } = require('child_process');
function execCommand(command) {
exec(command, (error, stdout, stderr) => {
if (error) {
b(`exec error: ${error}`);
return;
}
a(`stdout: ${stdout}`);
b(`stderr: ${stderr}`);
});
}
const commands = [
`git clone https://github.com/EliLillyCo/${repo}.git`,
`cd ${repo}`, `git checkout -b ${branch}`,
'cp ../codeql-analysis.yml .github/workflows/',
'git add .github/workflows/codeql-analysis.yml',
`git push --set-upstream origin ${branch}`,
'cd ../',
`rm -r ${repo}`,
];
for (let i = 0; i < commands.length; i++) {
setTimeout(execCommand(commands[i]), 3000);
}
但是setTimeout() 有问题,因为它返回了这个:
worker:error TypeError [ERR_INVALID_CALLBACK]: Callback must be a function. Received undefined
在使用超时的同时,解决顺序循环数组问题的最佳方法是什么?
【问题讨论】:
-
正确的语法是
setTimeout( execCommand, 3000)或setTimeout( () => { execCommand(commands[i]) } , 3000)
标签: javascript node.js arrays loops timeout