DEV Community

Discussion on: Storing permissions ~ AoaH Nine

Collapse
 
avalander profile image
Avalander • Edited

My question is when a class needs to wait before it can be used is it ok to .then even though it's messy or is there a better way I don't know?

I assume you need a Promise because you are initialising a connection to the database or something similar. In that case, I would just have a setup function for your app that would run after the connection is established and inject the connection to whatever object needs it.

This is an example of what I mean.

initDb()
  .then(db => {
    const getPonies = makeGetPonies(db)
    const insertPony = makeInsertPony(db)

    app(getPonies, insertPony).start()
  })

If you want to see it in the real world, I initialise an express server using this method here.

That being said, since the queries to the database are asynchronous and will return a Promise anyway, it doesn't make a big difference. I think that waiting for the connection to the database to be resolved and then initialise your application is cleaner and easier in the long run, but that's just my personal preference.

Collapse
 
link2twenty profile image
Andrew Bone

Is that better than having an init function with the class?

Collapse
 
avalander profile image
Avalander

It's hard to say what is objectively better without being familiar with your code. I don't even know why you need a class at all if all it's doing is retrieving a user and their password from the database.

I like my approach because I can treat the connection to the database as a synchronous value in my entire application, which means less asynchronous code. Any code that has access to the connection, can use it as a regular object, no need to await for anything in case it hasn't been initialised.

With your approach, any function that queries the database needs to check if the connection object exists, and if it doesn't, call the function that creates it, and wait for the promise to resolve. If you only query the database in one place, it's fine, but I can imagine it becoming harder the more different queries you need to do against the database.

Then again, I might have entirely misunderstood your code.

Thread Thread
 
link2twenty profile image
Andrew Bone

I was only using a class as a place to store lots of functions. I guess it makes sense to have a bunch of functions that you pass the database to as an argument.

Thank you 🙂