Skip to content

Instantly share code, notes, and snippets.

@raybellis
Last active July 7, 2017 05:53
Show Gist options
  • Save raybellis/b6594bfb240864b37a32 to your computer and use it in GitHub Desktop.
Save raybellis/b6594bfb240864b37a32 to your computer and use it in GitHub Desktop.
Async Mongo test
var MongoClient = require('mongodb').MongoClient;
var Q = require('q');
function connect(url) {
var def = Q.defer();
MongoClient.connect(url, function(err, db) {
if (err) {
def.reject(err);
} else {
def.resolve(db);
}
});
return def.promise;
}
function doStuff() {
return connect('mongodb://localhost:27017/test').then(function(db) {
var promises = [];
var collection = db.collection('test');
var cursor = collection.find({});
var done = Q.defer();
cursor.each(function(err, item) {
if (err) {
done.reject(err);
} else if (item === null) {
done.resolve();
} else {
var def = Q.defer();
promises.push(def);
// use item
console.log(item);
def.resolve();
}
});
return (done.promise).then(function() {
return Q.all(promises).then(function() {
db.close();
});
});
});
};
function myCallback() {
console.log('Hey, it worked!');
};
doStuff().then(myCallback).catch(function(e) {
console.log('Whoops! - ' + e);
});
@krishnarajloganatan
Copy link

Thanks for the wonderful example.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment