Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

203
Vistas
NodeJS: How to delay a module's resolution due to the dependencies on that module

Suppose the following scenario:

We have a class that handles a Mongoose connection as below:

export interface IInstance {
  name: string;
  instance: Mongoose.Mongoose;
}

export default class MongoHandler {

  public static instances: IInstance[] = [{
    name: 'default',
    instance: null,
  }];

  // Connect to mongo instance and add it to the instances array
  public static async connect(name: string, uri: string, options?: object): Promise<void> {
    const instance: Mongoose.Mongoose = await Mongoose.connect(uri, options);
    const newInstance: IInstance = {
      name,
      instance,
    };
    MongoHandler.instances.push(newInstance);
  }

  // Returns the instance based on the name of instance
  public static getInstance(name: string = 'default'): Mongoose.Mongoose {
    return this.instances.find(instance => instance.name === name).instance;
  }
}

The other module called CarModel is using getInstance() method for creating a model:

export interface ICar {
  name: string;
}

const carSchema = new Mongoose.Schema<ICar>(
  {
    name: {
      type: String,
      required: true,
    },
  }
);

const carModel = MongoHandler.getInstance('default').model<ICar>('Car', carSchema, 'Cars');
export default carModel;

We are using carModel in a module called CarController.

In index.ts we are calling these two modules as below:

import 
const app = new App(
  [
    MongoHandler.connect('default', process.env.MONGO_URI),
  ],
  [
    new CarController(),
  ]
);

App is a class for handling express bootstrapping (can be ignored).

While running this code MongoHandler.getInstance('default') is undefined because of the order of dependency resolution (I think)! And resolving MongoHandler.getInstance('default') is followed by MongoHandler.connect() which should be reversed.

How can I solve this?

Best regards

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I think there are 2 issues at play here, neither of them having to do with module resolution (which will work just fine as you don't have any circular dependencies).

  1. array.prototype.find returns the FIRST match found, you instantiate instances array with an object that matches the name default, but has no instance. When you connect, you add another object with the name default, but this will be second in the list, thus find will return the original object, which has its instance object set as null. I would advice removing this default empty instance object for error and code clarity.

  2. your connect function makes use of async-await. But you never await your connect function, thus not guaranteeing that your new connection instance has been made before you are calling getInstance inside of your carController. You should catch the Promise returned by the connect function and await it. If you do not want to delay your CarController instantiation, you can use save this Promise in the MongoHandler and return it with some init function that you call inside of the CarController to make sure the connect has been resolved.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda