TheUnreal
TheUnreal

Reputation: 24462

Nodejs - share variable created asynchronously between multiple files

I'm using NodeJS / Express.

In my app.js, I have a variable retrieved asynchronously that I want to share between multiple files:

const myDriver;
somePromise.then((driver) => myDriver = driver);

somePromise creates a driver instance of selenium.

My goal: share the value of myDriver between multiple files in my express project, after the promise has resolved, without executing the promise multiple times (so it won't create multiple selenium instances). I need to do it only when the app starts.

I couldn't find the right usage with module.exports since it's async.

Any idea?

Upvotes: 1

Views: 121

Answers (1)

Ashish Modi
Ashish Modi

Reputation: 7770

Something like this should do the trick. Basically save the instance somewhere so you can reuse it in subsequent calls.

let myDriver;

async function getDriver() {
  if (!myDriver) {
    myDriver = await somePromise();
  }

  return myDriver;
}

module.exports = getDriver;

usage

const driver = await getDriver();

Since it is await, you need to use async for the functions.

Upvotes: 1

Related Questions