Node.js如果没有错误,回调函数需要 null?



看看mongodb驱动程序的示例代码: http://mongodb.github.io/node-mongodb-native/2.2/tutorials/projections/

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);
});
}

最后一行回调(文档(不是回调(空,文档(?

这取决于您的回调。

有错误优先回调,它确实将错误作为第一个参数,将数据作为第二个参数,如:callback (err, data)

但是,在 Mongo 的官方示例网页(您指出的网页(中,他们传递了一个没有错误参数的回调。错误优先回调在 Node 的内置模块中无处不在,但 Node 不会以任何方式强制您使用它们。在这个例子中,这就是Mongo开发人员决定做的事情。

不过,您可以轻松地重写 Mongo 示例以使用错误优先回调。

最新更新