2013-11-21 114 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