如何避免nodejs回调地狱?

时间:2015-03-06 14:09:57

标签: javascript node.js mongodb asynchronous callback

我是node / Mongo的新手,我已经运行了我收集的内容"回调地狱"。这是我从书中复制的一个简单例子。它只是连接到mongo,添加和删除集合并记录这些操作:



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




此代码有效,但它似乎很难阅读和维护。我一直在研究如何处理这个问题,似乎有不同的意见。如果有人可以提供另一种方法对此进行编码,哪个库依赖项(如果有的话)做得最好,并重新编写此示例,那将非常感谢!!!

0 个答案:

没有答案
相关问题