I want to rewrite this function to resolve the promise instead of calling the callback function in an attempt to better understand working with promises.
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);
});
};
However, I don't seem to be able to. I already tried the naive approach of doing
export const connect = (): Promise<void> => new Promise((resolve): void => {
// ...´
.then((result) => {
LOG.debug("Connection established");
connection = result;
resolve();
})
// ...
});
But this doesn't correctly resolve when the connection was established.
What am I doing wrong? How can I rewrite this to properly use and resolve the Promise instead of using a callback function?