我遇到需要同步执行exec的情况。怎么办?我找到了一个lib execSync。但它是折旧的。所以任何其他解决方案。我可以使用蓝鸟承诺吗?
for (var i = 0; i < testCasesLength; i++) {
var currentTestCase = testCases[i];
output.testCases.push({ passed: false, name: currentTestCase.name, input: currentTestCase.name, output: null });
fs.writeFileSync(path + "/input" + i + ".txt", currentTestCase.input);
var command = "cd " + path + " & java Main < input" + i + ".txt";
exec(command, function(error, stdout, stderr) {
if (error) {
if (exports.stats) {
console.log('INFO: '.green + path + '/Main.java contained an error while executing');
}
if (error.toString().indexOf('Error: stdout maxBuffer exceeded.') != -1) {
output.error = 'Error: stdout maxBuffer exceeded. You might have initialized an infinite loop.';
fn(output);
} else {
output.error = stderr;
fn(output);
}
} else {
if (exports.stats) {
console.log('INFO: '.green + path + '/Main.java successfully compiled and executed !');
}
// On success test Running
if (stdout == currentTestCase.output) {
output.testCases[i].passed = true;
output.score = output.score + parseInt(currentTestCase.score);
} else {
output.testCases[i].output = stdout;
}
}
});
}
fn(output);
答案 0 :(得分:1)
我建议使用带有async功能的eachSeries模块来实现同步性
async.eachSeries(testCasesLength,function(item,callback){
//return callback after exec command completed, the next iteration will not execute until get callback()
});