How to export variables that are assigned inside a callback function?

Viewed 39

I am trying to create multiple DB connections. The problem is in order to get the DB connection string, I have to call an asynchronous function (getDBString). This asynchronous function returns the correct DB string. After that, I have to export the connection variables. I have a doubt. Will the conn1, conn2, and conn3 variables are assigned correct values coming from the async functions? or will they be unassinged when exporting? I am a newbie and can anyone explain when these callbacks run and when the export statement runs?

import mongoose from 'mongoose';
import dbConfiguration from '../config';
import DBString from '../utils/DBString';

let conn1 = DBString.getDBString(dbConfiguration.endpoint1).then( connString => mongoose.createConnection(connString, {}));
let conn2 = DBString.getDBString(dbConfiguration.endpoint2).then( connString => mongoose.createConnection(connString, {}));
let conn3 = DBString.getDBString(dbConfiguration.endpoint3).then( connString => mongoose.createConnection(connString, {}));

export {conn1 ,conn2 ,conn3}
1 Answers

As per your code, the conn1, conn2, and conn3 will not be unassigned or undefined. A promise object for each variable will be assigned. Thus, wherever you import these variables, you will have access to those Promise objects.

First, because you haven't provide getDBSting function. I have wrote a sample function that mimics the said behavior that returns a Promise. The Promise will be resolved with a DB string.

export default class DBString {
  static getDBString = (endPoint) => {
    return new Promise((resolve, reject) => {
      const delay = Math.floor(Math.random() * 5000);
      setTimeout(() => {
        if (delay > 4950) {
          reject("Connection Timeout.");
        } else {
          resolve(`db://yourDbString//${endPoint}`);
        }
      }, delay);
    });
  };
}

As I said earlier, when you import conn1, conn2, and conn3, you have access to the promise object returned. Thus, you can call the then method on these promise objects like this.

import { conn1, conn2, conn3 } from "./db.js";

conn1.then((connString) => console.log(connString));
conn2.then((connString) => console.log(connString));
conn3.then((connString) => console.log(connString));

Or, a better approach is to make conn1, conn2, and conn3 into asynchronous functions like this.

import DBString from "./dbString.js";

const conn1 = async () => {
  const connString = await DBString.getDBString("dbConfiguration.endpoint1");
  return `established connection: ${connString}`;
};

const conn2 = async () => {
  const connString = await DBString.getDBString("dbConfiguration.endpoint2");
  return `established connection: ${connString}`;
};

const conn3 = async () => {
  const connString =  await DBString.getDBString("dbConfiguration.endpoint3");
  return `established connection: ${connString}`;
};

export { conn1, conn2, conn3 };

Again, you can call the then method on the Promise object like this.

conn1().then((connString) => console.log(connString));
conn2().then((connString) => console.log(connString));
conn3().then((connString) => console.log(connString));
Related