0

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");
    })
});
Mindaugas Bernatavičius
  • 3,757
  • 4
  • 31
  • 58
  • After some additional research, it seems to not make sense to expect async call to result be printed in a synchronous contex (the outtest programm scope). Like stated here: https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – Mindaugas Bernatavičius Jul 18 '17 at 10:44

1 Answers1

0

You can simply use Promise to return the result like this.

 var Q = require('q');
 var deferred = Q.defer();

 MongoClient.connect(url, function(err, db) {
        if(err) throw err;
        db.collection('Col')
                .find(
                    { "Name": { $regex: /t/i}}, {"_id": 1}
                ).toArray(function(err, res){
                     if(err)
                       deferred.reject(err);
                     if(res.length > 1 ){
                       console.log("More than one");
                     } else if (res.length < 1) {
                       console.log("Less than one");
                     } else {
                       console.log(res);
                     }
                     deferred.resolve(res);
                });  
                return deferred.promise;

        db.close(function(){
            console.log("Close connection");
        })
    });
Kamesh
  • 1,122
  • 9
  • 12