-2

I have two files

server.js

(function () {
  var x = modules.dbFind('7');
  setTimeout(function() {
      console.log(x);
  }, 100);
})();

and my modules.js

var dbFind = (id) => {
    console.log("dbFIND function in use!");
    MongoClient.connect(url, function(err, db) {
        if (err) throw err;
        db.collection("users").findOne({id:id}, function(err, result) {
            if (err) throw err;
            console.log(JSON.stringify(result));
            return(result);
            db.close();
        });
    });
};

I want to pass RESULT from modules to the server file and read it there but x = undefined. Result in modules.js - console.log(result) shows all as I wish.

I know that the problem is in reading X before result gets there - but I trying already couple days and I have no idea how to solve it.

Cœur
  • 37,241
  • 25
  • 195
  • 267
BatOOn
  • 131
  • 8
  • You should use async wait to get value x. When you `x` value was assigned, dbFind was not finished. – sungyong Dec 15 '17 at 12:00

2 Answers2

1

Change as below. If you use promise/then, you don't need to wait as setTimeout.

server.js

(async function () {
  modules.dbFind('7')
          .then((result)=> {
            console.log(result);
          });
})();

modules.js

function dbFind(id) {
    return new Promise((resolve, reject)=> {
        console.log("dbFIND function in use!");
        MongoClient.connect(url, function(err, db) {
            if (err) reject(err);
            db.collection("users").findOne({id:id}, function(err, result) {
                if (err) reject(err);
                console.log(JSON.stringify(result));
                resolve(result);
                db.close();
            });
        });    
    });
}
sungyong
  • 2,267
  • 8
  • 38
  • 66
0

Since this is tagged promise you can just use async/await and the fact MongoClient contains promises. Otherwise this is a duplicate of this question:

const dbFind = async (id) => {
  console.log("dbFIND function in use!");
  const db = await MongoClient.connect(url)); // no callback = return promise
  try {
    let user = db.collection("users").findOne({id}); // shorthand {id:id}
    return user; 
  } finally {
    db.close();
  }
}

This would let you do:

(async () =>
  let found = await modules.dbFind('7');
  console.log(found);
})()

Also note, Mongo connections should be persistent and opened once per app vs. for every request.

Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
  • there are some mistakes but even I correct them I get in console: UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: module.dbFind is not a function What does it mean? there is not too much help in google for this error – BatOOn Dec 15 '17 at 13:15
  • You didn't require the other file as module – Benjamin Gruenbaum Dec 15 '17 at 17:36