如何同步使用node exec?

时间:2016-10-26 07:42:18

标签: javascript node.js exec mean-stack bluebird

我遇到需要同步执行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);

1 个答案:

答案 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()
});