Timeout with Promise

I'm looking to enhance my understanding of working with promises by rewriting this function to resolve the promise instead of resorting to calling the callback function.

export const connect = (callback: CallableFunction|void): void => {
    LOG.debug("Connecting to DB at %s", URI);

    connectToMongoDb(URI, opts)
        .then((result) => {
            LOG.debug("Connection established");
            connection = result;

            if (callback) {
                callback();
            }
        })
        .catch((err) => {
            LOG.error("Could not establish connection to %s, retrying...", URI);
            LOG.error(err);
            setTimeout(() => connect(callback), 5000);
        });
};

Despite several attempts, I have been unable to do so. My initial approach was:

export const connect = (): Promise<void> => new Promise((resolve): void => {
    // ...´
        .then((result) => {
            LOG.debug("Connection established");
            connection = result;
            resolve();
        })
    // ...
});

Unfortunately, this method does not properly resolve when the connection is established.

What could be the issue here? How can I rephrase this to effectively utilize and resolve the Promise without the need for a callback function?

Answer №1

Upon reviewing the feedback, I successfully restructured the function to ensure it returns a promise that resolves only when the connection is established:

const pause = (ms: number): Promise<void> =>
    new Promise((resolve): void => {
        setTimeout(resolve, ms);
    });

export const establishConnection = (): Promise<void> => {
    LOG.info("Initiating connection with DB at %s", URI);

    return connectToDatabase(URI, opts)
        .then((result) => {
            LOG.info("Connection with DB has been established");
            connection = result;
        })
        .catch((err) => {
            LOG.error("Unable to establish connection with %s, retrying...", URI);
            LOG.error(err);
            return pause(5000).then(establishConnection); //retry after 5 seconds
        });
};

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

Is there a specific instance where it would be more appropriate to utilize the styled API for styling as opposed to the sx prop in Material-

I am currently in the process of migrating an existing codebase to Material UI and am working towards establishing a styling standard for our components moving forward. In a previous project, all components were styled using the sx prop without encounteri ...

"Error encountered: Unable to resolve dependency tree" message appears when attempting to run npm install

Encountering dependency errors while trying to execute the npm install command for my Angular application. As a newcomer to TypeScript and Angular, I'm unsure of the next steps to take. Any suggestions? Attempted solutions include clearing the npm ca ...

Angular and TypeScript make a powerful combination when working with the mat-table component

I'm currently working with Angular's mat-table component. One challenge I'm facing is setting a caption for the table. <table mat-table [dataSource]="dataSource" class="mat-elevation-z8" id=tbl_suchergebnis> <caption> ...

Aligning Description Item components horizontally in antdLearn how to easily horizontally align Description

Currently, I am utilizing the `antd` Description components. In this scenario, when there is no `title` for the items, the value should be aligned to the left. You can see an example of this alignment in the image below: I have attempted to fix this issu ...

The Environment variable in React Native is not functioning when utilizing TypeScript

After installing the react-native-dotenv library, I followed the instructions outlined in the TypeScript guide. I then created a .env file with the following contents: MARVEL_API = <url> MARVEL_PUBLIC_KEY = <public-key> MARVEL_PRIVATE_KEY = &l ...

Typescript loading icon directive

Seeking to create an AngularJS directive in TypeScript that wraps each $http get request with a boolean parameter "isShow" to monitor the request status and dynamically show/hide the HTML element depending on it (without utilizing $scope or $watch). Any ...

Avoiding repetitive logic in both parent and child components in Angular 8

In my parent controller, I have common requests and I also read router params for those requests. However, for the child components, I have different requests but still need to extract the same parameters from the router - resulting in duplicate code. For ...

What is the best way to output a JSX element using an inline switch statement?

I have been attempting to use an inline switch in order to return an element, but all I am getting is an empty <span> </span>. What could be the issue here? getRowTdForHeader: (header: string, entry: response) => { return (< ...

React Router Issue: Component Not Rendering When <nav> Element Is Incomplete

I am currently experiencing an issue with rendering a component in my React TypeScript application using React Router. The problem arises when trying to navigate to the AddTask component by clicking on a link within a <nav> element. Strangely, the co ...

Implementing redux-persist with redux toolkit using TypeScript

Currently, I have been utilizing Redux Persist in my next js application but now I am interested in incorporating redux toolkit with TypeScript. While I have managed to grasp the syntax for implementing redux-persist in redux toolkit, I am struggling to ...

What is the best way to configure webpack for ng build instead of ng serve?

My .NET web application is hosted in IIS and it also hosts an Angular application. This setup requires both applications to be served on the same port by IIS, primarily because they share the same session cookie. Additionally, they are integral parts of th ...

Document: include checksum in HTML

I have a set of three files. The file named loader.js is responsible for creating an iframe that loads another file called content.html, which in turn loads content.js. I have made loader.js publicly available so that other users can include it on their ow ...

How can I retrieve routing parameters in a Vue.js/Nuxt/TypeScript app?

In the process of developing my website based on the Nuxt TypeScript Starter template, I've encountered a challenge. Specifically, I have created a dynamically routed page named _id.vue within my pages folder and am looking to access the id property i ...

When a module is generated, it appends an additional slash to the path in the app.module.ts file

I've noticed a strange behavior with the generator in Angular CLI tools that adds an extra slash character for modules. For example, when running ng generate component visual a line like this is added to the app.module.ts file import { VisualCo ...

Leveraging IF conditions on part of the worksheet title

Currently, my script is performing the task of hiding three columns for tabs in a workbook that start with "TRI". However, the execution speed is quite sluggish. I am seeking suggestions on how to optimize and enhance the performance. If possible, please p ...

React | Utilizing ForwardedRefs with React Components

I'm currently working on a React project where I am creating a custom component that needs to be exported using forwardedRef. However, as I attempt to do this, an error keeps popping up: error This is the code snippet causing the issue: export inter ...

Using vue-router within a pinia store: a step-by-step guide

I'm currently setting up an authentication store using Firebase, and I want to direct users to the login/logged page based on their authentication status. My goal is similar to this implementation: https://github.com/dannyconnell/vue-composition-api- ...

Having trouble finding the "make:migration" command in Adonis 5 - any suggestions?

After reviewing the introductory documentation for Adonis Js5, I attempted to create a new API server. However, when compiling the code using "node ace serve --watch" or "node ace build --watch", I kept receiving an error stating "make:migration command no ...

The Element type does no feature a Typescript property

Despite my attempts to include a declaration file and various other solutions, I'm still struggling with this issue: The goal is to define the visible property as a function on the HTML Element object. However, the linter keeps flagging visible with ...

What is the proper way to define the type for a functional React component by using object destructuring on props?

As I continue to learn TypeScript and work on declaring advanced types, I am faced with converting my CRA project to TypeScript. Within this project, I have a component that closely resembles examples from react-router-dom, but I have not come across any T ...