Here is the code snippet used to initialize a gRPC server:
export const initServer = async (finalPort: number): Promise<string> => {
let initStatus = 'initial';
gRPCserver.addService(webcomponentHandler.service, webcomponentHandler.handler);
// define the host/port for the server
await gRPCserver.bindAsync(
`localhost:${finalPort}`,
grpc.ServerCredentials.createInsecure(),
(err: Error | null, port1: number) => {
if (err != null) {
console.error(err);
log.info('Biding Error');
initStatus = 'Binding Error';
}
// start the gRPC server
gRPCserver.start();
log.info(`startServer::gRPC server started, on port: ${port1}`);
initStatus = 'OK';
},
);
return initStatus;
};
I need to return the initStatus variable to this function:
type StartServerType = () => Promise<string | undefined>;
export const startServer: StartServerType = async (): Promise<string | undefined> => {
try {
let initStatusResponse;
// Get the port
const finalPort = port();
await server.initServer(finalPort).then((res) => {
initStatusResponse = res;
log.info('INIT STATUS RESPONSE: ', initStatusResponse);
});
} catch (e: unknown) {
if (typeof e === 'string') {
return e.toUpperCase(); // works, narrowing down to string type
}
if (e instanceof Error) {
return e.message; // works, narrowing down to Error type
}
}
return 'started';
};
However, I always get 'initial' as the initStatusResponse value. There seems to be an issue related to asynchronous processing, but I can't pinpoint where exactly.
Appreciate any help in advance.