Node.js: Using Promises with MongoDb

I started using the Q Promise package in a simple node.js application. Therefore, I am wondering how I can close the db connection after completing the sequence of promises.

Example:

var toDbConnectionString = function(dbSettings) {
    return "mongodb://" +
        dbSettings.user + ":" +
        dbSettings.password + "@" +
        dbSettings.url;
};

var connectionString = toDbConnectionString(dbSettings);

Q.nfcall(
    MongoClient.connect,
    toDbConnectionString(dbSettings))
.then(function(db) {
    return Q.ninvoke(db, "collectionNames");
})
.then(function(collections) {
    console.log(collections);
})
.catch(function() {
    console.log(arguments);
});

I want to close the connection after displaying the collection names, but there is no db context in this anonymous function.

Is there a way to handle such cases with a promise template?

+4
source share
2 answers

You can thennest-callbacks arbitrarily. Yes, it is getting closer to the doom pyramid, but this is the only way to preserve the arguments in the scope. In your case:

Q.nfcall(
    MongoClient.connect,
    toDbConnectionString(dbSettings))
.then(function(db) {
    return Q.ninvoke(db, "collectionNames")
    .then(function(collections) {
        console.log(collections);
    }).finally(function() {
        db.close();
    });
})
.catch(console.log.bind(console));

, .

+3

(, , ...), :

var toDbConnectionString = function(dbSettings) {
    return "mongodb://" +
        dbSettings.user + ":" +
        dbSettings.password + "@" +
        dbSettings.url;
};

var connectionString = toDbConnectionString(dbSettings);
var db;

Q.nfcall(
    MongoClient.connect,
    toDbConnectionString(dbSettings))
.then(function(_db) {
    db = _db;
    return Q.ninvoke(db, "collectionNames");
})
.then(function(collections) {
    console.log(collections);
})
.catch(function() {
    console.log(arguments);
})
.finally(function() {
    if (db) db.close();
});
+4

All Articles