0

I am creating a simple node script to learn the functionality of Cosmos DB. I want to create a way to not have to provide the following at the top of every async function (yes, I know I could chain the async calls with but that means still means I have to use a new db instance at the top of every function. So, I want to do something like this:

const {database} = await client.databases.createIfNotExists({id: databaseId});
const {container} = await database.containers.createIfNotExists({id: containerId});

With that said, I've bumped my head on this for a few hours and can't find a way to create one database and one container for all my functions to share. The idea (but not implementation because it doesn't work, is to do something like this:

getConnections = async () => {

    const {database} = await client.databases.createIfNotExists({id: databaseId});
    const {container} = await database.containers.createIfNotExists({id: containerId});

    let connections = {};
     connections.db = database;
     connections.container = container;

    return connections;
};

But since the getCoonections method is async (which it must be because the methods that would use it are, too) the function doesn't necessarily finish before the first insert is made in another function, thereby causing an exception.

Has anyone found a way to centralize these objects so I don't have to declare them in each async function of my app?

José Pedro
  • 1,097
  • 3
  • 14
  • 24
  • What exactly does "*each async function of my app*" mean? Do *all* of your functions use those two objects? How are all the functions called? Are they organised in methods of instances or something? And does your app have some kind of `main` function or entry point? – Bergi Oct 23 '18 at 18:27
  • See also [this answer](https://stackoverflow.com/a/45448272/1048572) for a generic approach. – Bergi Oct 23 '18 at 18:28

2 Answers2

1

It sounds like you need to get these connections before the app does anything else. So why not simply make the loading of your app use async/await too?

async function init() {
  const connections = await getConnections();
  const app = initializeTheRestOfYourApp(connections); // now safe to do inserts
};
init();
Alex Wayne
  • 178,991
  • 47
  • 309
  • 337
0

This pretty much works now, Not sure why as there is no blocking between this init() and the next async method in the call chain uses the connection, but it's working. – David Starr - Elegant Code just now