回调异常[TypeError: listener必须是一个函数]

Callback exception [TypeError: listener must be a function]

本文关键字:一个 函数 异常 TypeError listener 回调      更新时间:2023-09-26

我写了一个简单的NodeJS程序来执行shell脚本。我fork出一个子程序并尝试执行该脚本。我在退出时为子进程提供了一个回调,如下所示。但是当我试图运行程序时,它抛出了一个异常。我哪里做错了?

var exec = require('child_process').exec;
function callXmlAgent(callback) {
    try {
        var child = exec('./a.sh');
        var response = { stdout: '', stderr: '', errCode: -1 };
        child.stdout.on('data', function (data) {
            response.stdout += data;
        });
        child.stderr.on('data', function (data) {
            response.stderr += data;
        });
        child.on('close', function (errCode) {
            if (errCode) {
                response.errCode = errCode;
            }
        });
        child.on('exit', callback(response));
        process.on('exit', function () {
            // If by chance the parent exits, the child is killed instantly
            child.kill();
        });
    } catch(exception) {
        console.log(exception);
    }
}
function foo(response) {
    console.log(response)
};
callXmlAgent(foo);
我得到的输出是:
{ stdout: '', stderr: '', errCode: -1 }
[TypeError: listener must be a function]

用以下代码修改子退出事件:

child.on('exit', function() {
   callback(response);
});

现在它不再抛出错误了,但是要注意,使用异步数据并不能保证执行的顺序,所以你可能会得到意想不到的结果。

问题是你不能在另一个函数中传递带有参数的函数。您必须创建一个匿名函数,并在其中发送参数。