nostyn
nostyn

Reputation: 3

NodeJS | Wait for an operation to finish in another script

Long story short, I would like the object exported from myModule to be created only after the first script is connected to the db; and then share myObject with any scripts that need it. Can this be done? What are the smarter alternatives to do the same things?

//mainapp.js

const mongoose = require('mongoose');

/*application setup stuff*/

mongoose.connect(/*...*/);
//myModule.js

const mongoose = require('mongoose');

class myClass {
  constructor(){
    /*db operations*/
    this.myVar = /*...*/;
  }
}

module.exports = new myClass();
//script.js,script2.js,script3.js...

import myObject = require('./myModule');

/*...*/ = myObject.myVar;

Upvotes: 0

Views: 90

Answers (1)

Rukshan Jayasekara
Rukshan Jayasekara

Reputation: 1985

I would like the object exported from myModule to be created only after the first script is connected to the db

You can start the server only if the the database connection was successfully established.

const app = express();

mongoose.connect(/*...*/).then(() => {
      app.listen(process.env.PORT, () =>
      console.log(`Example app listening on port ${process.env.PORT}!`),
    );
}).catch((err) => console.error(err));

Upvotes: 1

Related Questions