3 回答

TA貢獻1936條經驗 獲得超7個贊
var myCallback = function(data) {
console.log('got data: '+data);
};
var usingItNow = function(callback) {
callback('get it?');
};
現在打開節點或瀏覽器控制臺并粘貼上面的定義。
最后在下一行使用它:
usingItNow(myCallback);
關于節點式錯誤約定
Costa問我們如果要遵守節點錯誤回調約定會是什么樣子。
在此約定中,回調應該期望至少接收一個參數,即第一個參數,作為錯誤。可選地,我們將具有一個或多個附加參數,具體取決于上下文。在這種情況下,上下文是我們上面的例子。
在這里,我在這個約定中重寫了我們的例子。
var myCallback = function(err, data) {
if (err) throw err; // Check for the error and throw if it exists.
console.log('got data: '+data); // Otherwise proceed as usual.
};
var usingItNow = function(callback) {
callback(null, 'get it?'); // I dont want to throw an error, so I pass null for the error argument
};
如果我們想模擬錯誤情況,我們可以像這樣定義usingItNow
var usingItNow = function(callback) {
var myError = new Error('My custom error!');
callback(myError, 'get it?'); // I send my error as the first argument.
};
最終用法與上面完全相同:
usingItNow(myCallback);
行為的唯一區別取決于usingItNow您定義的版本:向第一個參數的回調提供“truthy值”(一個Error對象)的那個,或者為錯誤參數提供null的那個版本。 。

TA貢獻1804條經驗 獲得超8個贊
這里是復制文本文件的例子fs.readFile
和fs.writeFile
:
var fs = require('fs');var copyFile = function(source, destination, next) { // we should read source file first fs.readFile(source, function(err, data) { if (err) return next(err); // error occurred // now we can write data to destination file fs.writeFile(destination, data, next); });};
這是使用copyFile
函數的一個例子:
copyFile('foo.txt', 'bar.txt', function(err) { if (err) { // either fs.readFile or fs.writeFile returned an error console.log(err.stack || err); } else { console.log('Success!'); }});
公共node.js模式表明回調函數的第一個參數是錯誤。您應該使用此模式,因為所有控制流模塊都依賴于它:
next(new Error('I cannot do it!')); // errornext(null, results); // no error occurred, return result
添加回答
舉報