0

i cant seem to make it work in order and it will return undefined every time so how can i make it so the console.log shows it after the function is done?

var MongoClient = require("mongodb").MongoClient;
var url = "mongodb://localhost:27017/";
let datad;
function search(dbol, collection, query, callback) {
  MongoClient.connect(url, function (err, db) {
    if (err) throw err;
    var dbo = db.db(dbol);
    dbo
      .collection(collection)
      .find(query)
      .toArray(function (err, result) {
        if (err) throw err;
        // console.log(result);
        datad = JSON.stringify(result);
        console.log(datad);
        db.close();
        return result;
      });
  });

  return datad;
}

var query = { user: "admin" };
console.log(search("storageinterface", "user", query));
console.log(datad);

the console.log inside the function gives the correct value but i cant get it out of the function in time

AKX
  • 152,115
  • 15
  • 115
  • 172
skeyvin
  • 3
  • 3
  • You can't make an asynchronous call synchronous. If you're open to using promises, promisifying the function would be easiest. See https://docs.mongodb.com/drivers/node/current/fundamentals/promises/#promises-and-callbacks – AKX Dec 07 '21 at 06:55
  • Depends on what you are trying to achieve. Either use promise or await/async. Or if you want some function to be executed only after search is done, maybe you can try using the callback param in the search function. – gvmani Dec 07 '21 at 07:14
  • Mostly a duplicate of [How to return an asynchronous response](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call). And, there is now way (in nodejs) to convert an asynchronous operation to a synchronous one. You cannot directly return an asynchronously retrieved value. Instead (as indicated in my link above), you must use a callback, a promise or an event to communicate back the asynchronous value. – jfriend00 Dec 07 '21 at 07:50

0 Answers0