Smoothing a nested callback

I have a problem learning how to use the programming callback method in Node.js. I have a query on a MongoDB database. If I pass a function to execute on the result, it works, but I would prefer to smooth it and return the value. Any help or direction regarding how to do this correctly is appreciated. Here is my code:

var getLots = function(response){
    db.open(function(err, db){
        db.collection('lots', function(err, collection){
            collection.find(function(err, cursor){
                cursor.toArray(function(err, items){
                    response(items);
                })
            })
        })
    })
}

I need something more:

lots = function(){
    console.log("Getting lots")
    return db.open(openCollection(err, db));
}

openCollection = function(err, db){
    console.log("Connected to lots");
    return (db.collection('lots',findLots(err, collection))
    );
}

findLots = function(err, collection){
    console.log("querying 2");
    return collection.find(getLots(err, cursor));
}

getLots = function(err, cursor) {
    console.log("Getting lots");
    return cursor.toArray();
}

If the final data set will depend on function calls.

, Node.js, , err . - , , . , , . , .

+3
2

, , node npm wiki\w631 > .js, caolan/async, async.waterfall , async .

:

function getLots(db, callback) {
   db.collection("lots", callback);
}

function findLots(collection, callback) {
    collection.find(callback);
}

function toArray(cursor, callback) {
    cursor.toArray(callback);
}

async.waterfall([db.open, getLots, find, toArray], function (err, items) {
    //items is the array of results
    //Do whatever you need here
    response(items);
});
+4

async - . Frame.js , . ( npm, async)

Frame:

Frame(function(next){
    db.open(next);
});
Frame(function(next, err, db){
    db.collection('lots', next);
});
Frame(function(next, err, collection){
    collection.find(next);
});
Frame(function(next, err, cursor){
    cursor.toArray(next);
});
Frame(function(next, err, items){
    response(items);
    next();
});
Frame.init();
0

All Articles