2013-11-21 72 views
-1

我有这样的代码:添加参数回调

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,为什么它现在赢了?

+0

当你写在你的问题语法无效的代码有点难以确定什么是真正的代码,因此你的问题。 –

+0

您提供的代码在尝试调用回调之前会与'SyntaxError:Unexpected token {'发生错误。 – Quentin

+0

你需要提供一个'(另一个函数'(所以我们可以看到它返回的内容)的(最小的)例子,并且替换你对'addn'的调用,这个函数本身不会出错。 – Quentin

回答

3

当您在传递一个回调函数,你忽略了(),否则该功能将立即执行,并且是毫无意义的,所以尝试:

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

并在代码

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

愚蠢的我,就是这样,我几乎所有的代码都是这样的 – DrakaSAN