2017-08-03 59 views
2

只看示例代碼MongoDB的驅動程序: http://mongodb.github.io/node-mongodb-native/2.2/tutorials/projections/如果沒有錯誤,node.js回調函數需要null?

var MongoClient = require('mongodb').MongoClient 
    , assert = require('assert'); 

// Connection URL 
var url = 'mongodb://localhost:27017/test'; 
// Use connect method to connect to the server 
MongoClient.connect(url, function(err, db) { 
    assert.equal(null, err); 
    console.log("Connected correctly to server"); 

    findDocuments(db, function() { 
    db.close(); 
    }); 
}); 


var findDocuments = function(db, callback) { 
    // Get the documents collection 
    var collection = db.collection('restaurants'); 
// Find some documents 
    collection.find({ 'cuisine' : 'Brazilian' }, { 'name' : 1, 'cuisine' : 1 }).toArray(function(err, docs) { 
    assert.equal(err, null); 
    console.log("Found the following records"); 
    console.log(docs) 
    callback(docs); 
    }); 
} 

Shouln't最後一行的回調(文檔)是回調(NULL,文檔)?

+0

根據node.js回調符號它應該,但開發人員可以使用自己的風格。在這種風格中,回調根本不接受「錯誤」。 – alexmac

回答

2

這取決於你的回調。

error-first callbacks,這確實會錯誤作爲第一個參數,數據的第二個參數,像:callback (err, data)

然而,在蒙戈的官方例如網頁(一個你指出)他們傳遞一個沒有錯誤參數的回調。 Error-first回調在Node的內置模塊中無處不在,但Node並不強制您使用它們。在這個例子中,Mongo開發者決定這麼做。

不過,您可以輕鬆地重寫Mongo示例以使用錯誤優先回調。

相關問題