0

I am new to node/Mongo, and I have already run what I gather is "callback hell". Here's a simple example I copied from the book. It simply connects to mongo, adds and drops a collection and logs these operations:

var MongoClient = require('mongodb').MongoClient;
MongoClient.connect("mongodb://dbadmin:da@localhost:27017/", function(err, db) {
    var newDB = db.db("newDB");
    newDB.collectionNames(function(err, collectionNames) {
        console.log("Initial collections: ");
        console.log(collectionNames);
        newDB.createCollection("newCollection", function (err, collection){
            newDB.collectionNames( function (err, collectionNames) {
                console.log("Collections after creation: ");
                console.log(collectionNames);
                newDB.dropCollection("newCollection", function (err, results) {
                    newDB.collectionNames( function (err, collectionNames) {
                        console.log("Collections after deletion: ");
                        console.log(collectionNames);
                        db.close();
                    });
                });
            });
        });
    });
});

This code works, but it already seems really hard to read and maintain. I have been researching what to do about this, and there seems to be differing opinions out there. If someone could offer an alternative way to code this, which library dependency, if any, does the best job, and a re-write of this example, it would be greatly appreciated!!!

Coco
  • 1,550
  • 3
  • 24
  • 43
  • Look at async.js, icedcoffeescript and fibers. – chridam Mar 06 '15 at 14:17
  • During your research you must already have come across some of the alternatives, in particular Promises and asynchronous sequence libraries like async and await. Your example isn't complex - try them out and see what works for you. – joews Mar 06 '15 at 14:18
  • http://stackoverflow.com/questions/4234619/how-to-avoid-long-nesting-of-asynchronous-functions-in-node-js – Guilherme Reda Mar 06 '15 at 14:18
  • There are many similar questions that have already addressed this one...http://stackoverflow.com/questions/18095107/callback-hell-in-nodejs?rq=1 – Yousef Mar 06 '15 at 14:22

0 Answers0