0

I have a server.js file in which I have:

const express = require('express');
const app = express();

let driver;

(async () => {    
  try {
    driver = await someAsyncFunction();
  } catch (err) {
    console.log(err);
  }
})();

const port = process.env.PORT;

app.listen(port, () => {
  console.log(`Server started on port ${port}.`);
});

module.exports = {
  app,
  driver,
};

However, the value of driver is undefined outside of the async function. How can I correctly assign a value to driver outside of the async function?

Aryan Firouzian
  • 1,940
  • 5
  • 27
  • 41
Colin Ricardo
  • 16,488
  • 11
  • 47
  • 80
  • 1
    you can't. module exports happens synchronously and do not re-evaluated if consumer imports it early. You should export awaitable instead and let consumer asynchronously wait for value. – OJ Kwon Feb 13 '18 at 17:50
  • 2
    You can't. Just don't. At best, export a promise. – Bergi Feb 13 '18 at 17:50
  • @OJKwon can you explain what you mean by "you should export awaitable instead"? – Colin Ricardo Feb 13 '18 at 17:52
  • Any value is "awaitable" in JavaScript (`await 5`) is perfectly valid. I think he means you should export a "Promise" – Paul Feb 13 '18 at 18:22

0 Answers0