Home > Software design >  Store object in memory from an async method
Store object in memory from an async method

Time:12-15

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?

CodePudding user response:

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;
  }
  • Related