I want to wrap some logic inside a function. The logic should evaluate a result of a promise and then return a value or throw an exception (conditional returned based on the value of a promise).
Let me share a simpliefied code:
function GetID(exp, db){
let rxPtt = new RegExp(exp, 'gi');
let tID = db.collection('Col').find(
{ "Name": { $regex: rxPtt }}, {"_id": 1}).toArray();
let retVal = null;
tID.then(function (x){
if(x.length > 1 ){
console.log("More than one");
} else if (x.length < 1) {
console.log("Less than one");
} else {
retVal = x;
}
});
return retVal;
}
MongoClient.connect(url, function(err, db) {
if(err) throw err;
console.log(GetID('t', db));
db.close(function(){
console.log("Close connection");
})
});
This returns:
# ./SmallScripts.js
null
Close connection
More than one
QUESTION: I'm interested in how to return the value conditionally from a promise wrapper. If I would just pass on the promise and finalize it at the end, it works (see below). However I wanted to wrap the entire logic into one place and just return the ID. Let me know on the correct way this should be done and any tips on how to think about it if possible. Thanks!
function X(db){
let r = db.collection('Col')
.find(
{ "Name": { $regex: /t/i}}, {"_id": 1}
).toArray();
return r;
}
MongoClient.connect(url, function(err, db) {
if(err) throw err;
let r = X(db);
r.then(function(res){
if(res.length > 1 ){
console.log("More than one");
} else if (res.length < 1) {
console.log("Less than one");
} else {
console.log(res);;
}
);
db.close(function(){
console.log("Close connection");
})
});