为回调添加参数

时间:2013-11-21 15:15:14

标签: javascript node.js

我有这段代码:

function addn (pathname, callback) {
    fs.readFile(pathname, 'utf-8', function (err, data) {
        fs.writeFile(pathname, data.replace(/>/g, '>\n'), function() {
            callback ();
        });
    });
};

但是当我称之为

addn('path/to/file', anotherfunction(whichhavecallback(){});

我收到此错误:

callback();
             ^
TypeError: undefined is not a function
    at /path/to/my/js.js:610:13
    at Object.oncomplete (fs.js:107:15)

当我调用console.log之类的简单函数时,它有用吗,为什么它现在不能用?

1 个答案:

答案 0 :(得分:3)

当您传入回调函数时,省略(),否则该函数将立即执行并且毫无意义,请尝试:

addn('path/to/file', anotherfunction);

并在您的代码中

callback (); //-< insert parameter here!
相关问题