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

104
Vistas
Store object in memory from an async method

I am trying to store an object in memory on Node.js. This object is created from an async method that is a call to an API. The thing is, this used to be a synchronous object that many parts of the application are importing, but now it is asynchronous. What I am trying to do is load this object in memory when I initialize the app so the files that are importing the synchronous object do not need to be refactored.

Example:

// Settings.js
class Settings {
  async build() {
    setTimeout(() => {
      return { app: 'settings' }
    }, 1000)
  }
}

//index.js - store object in memory when application is initialized
const intializeApp = async () => await new Settings().build()


//randomFile.js
import Settings from 'settings.js' //importing object {app: 'settings'}

How would I accomplish this?

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

0

You need to store the settings and expose a way to access them. Since you're using classes, you can provide a get method:

// Settings.js
class Settings {
  async build() {
    return new Promise(resolve => {
      setTimeout(() => {
        this.settings = { app: 'settings' };
        resolve(); // so the async function can tell when the timeout is done
      }, 1000);
    }
  }
  get() {
    return this.settings;
  }
}

// Need to create one instance so it's shared between all the files that it's imported
export default new Settings();

//index.js - store object in memory when application is initialized
const intializeApp = async () => await Settings().build()


//randomFile.js
import Settings from 'settings.js' 
const settings = Settings.get();
console.log(settings);
// logs object {app: 'settings'}

And if you are fine with get being async could have it lazily initialize if there's no settings yet:

  async get() {
    if (!this.settings) await this.build();
    return this.settings;
  }
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