向回调添加参数

add arguments to callback

本文关键字:参数 添加 回调      更新时间:2023-09-26

我有这个代码:

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这样的简单函数时,它就起作用了,为什么现在不行了?

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

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

在你的代码中

callback (); //-< insert parameter here!