Skip to content

Instantly share code, notes, and snippets.

@dineshsprabu
Created February 11, 2016 13:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dineshsprabu/254d390ecf9bca02deb5 to your computer and use it in GitHub Desktop.
Save dineshsprabu/254d390ecf9bca02deb5 to your computer and use it in GitHub Desktop.
[NodeJS] Return a promise from your own function
var mongo = require('mongodb');
var monk = require('monk');
var Promise = require('bluebird');
/* DB connection */
var dbName = ''
var db = monk('localhost:27017/'+dbName);
/* replace <collection-name> with your collection*/
var collection = db.get(<collection-name>);
/* function getting values from DB and returning a promise */
var getValues = function(){
return new Promise(function(resolve, reject){
collection.find({},{'name':1},function(err,docs){
if(err){reject(err);}
else{resolve(docs);}
});
});
}
/* calling the function */
getValues()
.then(function(data){
console.log(data);
db.close();
});
.catch(function(err){ console.log(err); });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment