Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

108
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda