I am looking to encapsulate some logic within a function. This logic will involve evaluating the result of a promise and then either returning a value or throwing an exception based on a conditional evaluation of the promise.
Here is a simplified version of the code:
function ObtainID(expression, database){
let regexPattern = new RegExp(expression, 'gi');
let targetID = database.collection('Col').find(
{ "Name": { $regex: regexPattern }}, {"_id": 1}).toArray();
let returnValue = null;
targetID.then(function (result){
if(result.length > 1 ){
console.log("More than one");
} else if (result.length < 1) {
console.log("Less than one");
} else {
returnValue = result;
}
});
return returnValue;
}
MongoClient.connect(url, function(error, database) {
if(error) throw error;
console.log(ObtainID('t', database));
database.close(function(){
console.log("Closing connection");
})
});
This outputs:
# ./SmallScripts.js
null
Closing connection
More than one
QUERY: I am curious about how to conditionally return a value from a promise wrapper. If I were to directly pass the promise and resolve it at the end, it functions correctly (as shown below). However, my intention was to consolidate all the logic into one place and simply return the ID. Kindly advise on the correct approach for this and any tips on how to handle it more efficiently. Thank you!
function DetermineX(database){
let result = database.collection('Col')
.find(
{ "Name": { $regex: /t/i}}, {"_id": 1}
).toArray();
return result;
}
MongoClient.connect(url, function(err, db) {
if(err) throw err;
let resolvedResult = DetermineX(db);
resolvedResult.then(function(outcome){
if(outcome.length > 1 ){
console.log("More than one");
} else if (outcome.length < 1) {
console.log("Less than one");
} else {
console.log(outcome);
}
);
db.close(function(){
console.log("Closing connection");
})
});