-2

//load.js

(async function (){
  try {
    await require('./dbConfig').connectMongoDB().then(data=>{
      console.log('data::::::::::::',data);
    })
    console.log('DB Connected');
  } catch (error) {
    console.log('Error in Connecting MONGODB',error);
  }
})()

//dbConfig.js

module.exports={
  connectMongoDB: async function(){
    try {
      Evolve.MongoClient.connect(url, function(err, data) {
        if (err) {
          MongoClient.close();
          return false
        } else {
          console.log("Connected to database");
          return data
        }
      })
    } catch (error) {
      console.log('Error in dbConfig',error);
    }
  }
}

***Order of output: output:

data:::::::::::: undefined

DB Connected

Connected to database***

**await not waiting to finised function and get .then() **

Craicerjack
  • 6,203
  • 2
  • 31
  • 39
Rishu Singh
  • 11
  • 1
  • 2
  • 1
    connectMongoDB does not return anything – epascarello Jul 27 '22 at 13:27
  • What @epascarello is saying is that the two return statements (return false and return data) are inside a callback function hence they are the return value of the callback function, not the return value of the outer connectMongoDB function. – jarmod Jul 27 '22 at 13:31
  • Putting the `async` keyword on the `connectMongoDB` function does not magically make it wait for the callback. You'd have to use `new Promise` to do that properly. However, you don't even need to do that, mongodb methods already do return promises natively - just don't pass a callback and write `const data = await Evolve.MongoClient.connect(url);`! – Bergi Jul 27 '22 at 14:13

1 Answers1

0

Your function connectMongoDB does not return a promise, therefore when using .then in your // load.js file, it is not waiting for anything to resolve.

The use of .then is a promise-based action, which means you must return a promise to chain events.

Try changing your method to return a promise:

module.exports={
  connectMongoDB: async function(){
    return new Promise(() => {
      // ...yourCode
    })
  }
}

If you're looking to utilise that try-catch to further throw an error to .catch(), you will need to reject the promise.

Promise Reject Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/reject

(Jarmod has made a good comment - At a glance, I completely missed that the data was in a callback. The callback is not returned to connectMongoDB)

I would also advise against using await myFunction().then() either await myFunction() or myFunction().then() it'll become hard to manage if you're jumping between them.

Shea Lavington
  • 436
  • 2
  • 7