You can start by defining each of the callbacks in this nested system as functions instead. So the basic idea is instead of doing
action(data, function (err, value) { if (err) { ... } ... })
you do
action(data, namedCallback)
function namedCallback(err, value) {
if (err) { ... }
....
nextAction(value, nextNamedCallback)
}
Things you should note about this implementation
- The variables that you want to share are defined in scope of all of the functions (see
var db
andvar collection
- In this implementation, all of the functions are callbacks, To use the series implementation, you need to split up the functions into functions which perform the action, not functions which handle the action when it is finished
- You should handle the err case in your callbacks properly
var MongoClient = require('../lib/mongodb').MongoClient
, format = require('util').format;
var host = process.env['MONGO_NODE_DRIVER_HOST'] != null ?
process.env['MONGO_NODE_DRIVER_HOST'] :
'localhost';
var port = process.env['MONGO_NODE_DRIVER_PORT'] != null ?
process.env['MONGO_NODE_DRIVER_PORT'] :
27017;
console.log("Connecting to " + host + ":" + port);
MongoClient.connect(
format("mongodb://%s:%s/node-mongo-examples?w=1", host, port)
onConnect)
var db
var collection
function onConnect(err, _db) {
db = _db
db.dropDatabase(onDrop);
}
function onDrop(err, result) {
collection = db.collection('test');
// Erase all records from the collection, if any
collection.remove({}, onRemove);
}
function onRemove(err, result) {
// Insert 3 records
for(var i = 0; i < 3; i++) {
collection.insert({ 'a': i }, { w: 0 });
}
collection.count(onCount)
}
function onCount(err, count) {
console.log("There are",
count,
"records in the test collection. Here they are:");
collection.find().each(onFind);
}
function onFind(err, item) {
if (item != null) {
console.dir(item);
console.log("created at " + new Date(item._id.generationTime) + "\n")
}
// Null signifies end of iterator
if (item == null) {
// Destory the collection
collection.drop(onEnd)
}
}
function onEnd(err, item) {
db.close();
}