Created
February 11, 2016 13:17
-
-
Save dineshsprabu/254d390ecf9bca02deb5 to your computer and use it in GitHub Desktop.
[NodeJS] Return a promise from your own function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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