2017-08-03 58 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示例以使用错误优先回调。

相关问题