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?