Function not invoked

After creating an object with database-related methods, I encountered a problem where the connection to the database was lost because the create method wasn't being called. Can someone shed light on this issue?

Before (It works):

export const connection = createConnection();

Index file:

import { connection } from "./utils/database";

async () => {
  try {
    await connection;
  } catch (error) {
    console.error(error);
  }
};

After:

export const connection = {
  async create() {
    console.log("not showing in console");
    await createConnection();
  },

  async close() {
    await getConnection().close();
  },
};

Index file:

import { connection } from "./utils/database";

async () => {
  try {
    await connection.create();
  } catch (error) {
    console.error(error);
  }
};

Answer №1

The arrow function you've created to wrap the try catch block seems to be inactive. In the past, it worked because the connection was established in another file with the call to createConnection(); the arrow function in index was also not invoked.

import { connection } from "./utils/database";

async () => {
  try {
    await connection.create();
  } catch (error) {
    console.error(error);
  }
}();

I understand the intention is for the entire program execution to wait for the database connection, but perhaps it would be more efficient to only wait within functions that require the connection. It may require some adjustment to fit into your application.

connection.create()
  .then(() => console.log('db connected'))
  .error(console.error);

There are various options for waiting for the database connection.

  1. A simple check like while(!dbconnection) {}
  2. Attach handlers that need the db connection only once it is connected, using an event or in the .then.
  3. Explore other potential solutions.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

adding new data rows to an existing data list using Angular

I am currently working on displaying data from a backend system. The data is coming from a table that receives new rows within a specific time frame. To retrieve these new rows, I have set up a mechanism using an Angular timer. My query pertains to the tem ...

Using Jest functions as object properties results in undefined behavior

I am faced with a challenge in my class where I need to mock an object along with its properties intercept(context: ExecutionContext) { const response = contect.switchToHttp().getResponse() // the chain that needs to be mocked if (response.headersSent ...

What is the most efficient way to update data multiple times by mapping over an array of keys in a react hook?

My question might not be articulated correctly. I'm facing an issue with dynamically translating my webpage using Microsoft's Cognitive Services Translator. I created a react hook for the translator, which works well when I need to translate a si ...

Leveraging the Angular (2) routerLinkActive directive to handle dynamic routes

Although my current approach works, I believe there may be a more efficient way to implement this in Angular. The situation is as follows: Imagine nested, inflected paths like /logos and /logo/:id The markup below functions as intended: <li class ...

Having trouble with Angular 6 Validators.pattern() RegEx Function?

I've been attempting to implement a regular expression with the Validators.pattern() for Angular 6 FormBuilder, but for some reason, the validation is not working as expected. I even tested the RegEx on https://codepen.io/devtips/pen/gzqKKP and it was ...

tsconfig is overlooking the specified "paths" in my Vue project configuration

Despite seeing this issue multiple times, I am facing a problem with my "paths" object not working as expected. Originally, it was set up like this: "paths": { "@/*": ["src/*"] }, I made updates to it and now it looks like ...

What is the best way to output data to the console from an observable subscription?

I was working with a simple function that is part of a service and returns an observable containing an object: private someData; getDataStream(): Observable<any> { return Observable.of(this.someData); } I decided to subscribe to this funct ...

What is the best way to inform TypeScript when my Type has been altered or narrowed down?

In my application, I have a class that contains the API code: export class Api { ... static requestData = async ( abortController: React.MutableRefObject<AbortController | null> ) => { // If previous request exists, cancel it if ...

Angular displays various divs depending on the search query entered or when there is no input provided

Hey there! I'm currently working on implementing a search feature in my Angular 14 + Ionic v6 application. The user can search for products using a search field, which triggers an API call. I have three specific scenarios that I need to address: If ...

Implementation of a nested interface using a generic and union types

I am seeking to create a custom type that will enable me to specify a property for a react component: type CustomType<T> = { base: T; tablet?: T; desktop?: T; }; export type ResponsiveCustomValue<T> = CustomType<T> | T; This ...

What are the reasons for discouraging the use of canActivate always returning false?

I've searched extensively to avoid duplicate postings and tried various solutions, but unfortunately, none of them have resolved the issue. My implementation of canActivate to secure a dashboard seems to be working properly, but it's always retu ...

Guide on utilizing a provider's variable in another provider within Ionic 2/3

In my code, I have a boolean variable called isConnection that is used to monitor network connection status. This variable is defined in a provider named 'network' and can be set to either true or false in different functions. Now, I need to acc ...

Array containing multiple service providers in Angular

I encountered a problem while utilizing multiple providers in my application: ERROR Error: No provider for Array! at injectionError (VM634 core.umd.js:1238) [angular] at noProviderError (VM634 core.umd.js:1276) [angular] at ReflectiveInjector_._throwOrNul ...

Using Formik: When the initial value is changed, the props.value will be updated

After the initial props are updated, it is important to also update the values in the forms accordingly. export default withFormik({ mapPropsToValues: (props: Props) => { return ( { id: props.initialData.id, ...

Convert a collection of Either<A, B> into an Either<A[], B[]> array

Looking to convert an array of type Either<A, B>[] into Either<A[], B[]> The goal here is to gather all the left-values (errors) if there is at least one, otherwise return all right answers. This task may appear straightforward, but my curren ...

Is the Cyrillic encoding feature not functioning properly in Angular 4 with .Net Core 2?

Struggling with handling Cyrillic characters in my current project. Utilizing .Net Core 2 along with Angular 4.2.5 I've noticed that displaying a string in the templates using {{ someCyrillicString }} works fine. However, encountering issues when tryi ...

Explaining the data link between a service and component: understanding Subject and BehaviorSubject

Can someone explain the concepts of Subject and BehaviorSubject in Angular to me? I'm new to Angular and struggling to understand. I've tried searching online, but I still can't grasp how they work. The same goes for Observable and Observer ...

What is the best way to retrieve the final value stored?

This is how I am using my Selector:- private loadTree() { this.loading = true; this.store.select(transitionListSelector).pipe().subscribe(data => { console.log(data); data.map(item => { console.log(item); this.tr ...

Gathering user key event input for a duration of 2 seconds before resetting it

I need help implementing a feature where I can clear the user's input text after 500ms if they are entering characters consecutively. private userInputTimer; private userInputText = ''; private handleEvent(event: KeyboardEvent): void { if ...

Storing Images in MongoDB Using the MEAN Stack

Currently, I am in the process of developing an angular application that utilizes a MongoDB based Database. One of the features I am working on involves allowing users to upload files and store them in the DB. The drag and drop UI has been implemented succ ...