Issues arise when attempting to utilize Async/Await with a gRPC method

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.

Answer №1

When examining the documentation for gRPCserver.bindAsync, it appears that this method does not return a promise object. This is likely due to the fact that a callback function is being passed as an argument. Promise objects eliminate the need for callback functions, often referred to as "callback hell". For more information on asynchronous actions in Javascript/Typescript, you can refer to this article.

One effective approach is to use async/await. If gRPCserver.bindAsync does not return a promise, we can "wrap" it in a promise. This can be achieved easily with node.js util promisify (Documentation), or manually with new Promise. To explore both methods further, you can check out this informative article.

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

Guide on activating an event when a slider image is updated using jquery

I am working on a project that includes a slider. I have been trying to trigger an event when the slider image changes, but so far using the classChange Event has not been successful. Here is the link to my code: [1] https://codepen.io/anon/pen/gzLYaO ...

Is it possible to deduce the types of a particular value based on an interface that is provided as a generic parameter?

As a newcomer to TypeScript, I may be approaching this issue the wrong way. I am curious if there is a generic type that can handle an interface like {[key: string]: string | boolean} and allow for knowing the specific type of any value inside the consumin ...

Switching the Require statement to an Import statement led to an error popping up

Currently, I am exploring the use of Ajv with typescript. import { Ajv } from "ajv"; let ajv = new Ajv({allErrors: true}); I have encountered an error and I'm unsure why it is occurring: [ts] 'Ajv' only refers to a type, but is being u ...

I am searching for an uncomplicated approach to eliminate duplicate arrays of objects

Question: const info=[ { id: 123, name: "dave", age: 23 , address:city:"chennai"}, { id: 456, name: "chris", age: 23, address:city:"delhi"}, { id: 789, name: "bob", age: 23, address:city:& ...

What is preventing the transfer of array[i].charAt(0).toUpperCase() to array[i][0]?

I am currently working on a JavaScript program that is designed to capitalize the first letter of each word in a string while converting every other character to lowercase. function titleCase(str) { str = str.toLowerCase(); var array = str.split(" " ...

Utilize React Helmet for Dynamic Page Titles

Currently, I am utilizing Gatsby with react-helmet to manage the title and meta tags in the head of my website. However, I am eager to find a way to also display this title in the actual text of the page through a global <Header /> component. In proj ...

Utilizing a d.ts Typescript Definition file for enhanced javascript intellisene within projects not using Typescript

I am currently working on a TypeScript project where I have set "declaration": true in tsconfig.json to generate a d.ts file. The generated d.ts file looks like this: /// <reference types="jquery" /> declare class KatApp implements IKatApp ...

Alter the style of a div by clicking on a button

Can the background image of a div be changed by selecting a button outside of the div? For example: HTML <div id="change"></div> <div id="buttons"> <button class="button1">this</button> <button class="button2"> ...

Establish a permanent code folding feature in the Monaco editor for enhanced text organization

I need help implementing persistent code folding on the Monaco editor. Specifically, I am unsure about: how to extract the view state when it changes; storing it in localstorage; and then restoring it when Monaco is loaded. Although I am aware of saveVie ...

Navigating the world of Typescript: mastering union types and handling diverse attributes

I am currently working on building a function that can accept two different types of input. type InputA = { name: string content: string color: string } type InputB = { name: string content: number } type Input = InputA | InputB As I try to impleme ...

Rails encountered a syntax error while attempting to parse JSON data, due to an unexpected character found at line 2, column 1

I'm a beginner when it comes to using AJAX in Ruby on Rails. What I'm trying to achieve is that when a user clicks on a link with the class .link (redirecting to an external site, for example www.google.de), it should send data - specifically the ...

JavaScript source control tool

Is there a Java-based version of GitHub? I am interested in developing a dynamic application using HTML5 and Javascript, and had the thought of integrating Git to monitor data changes. Therefore, I am curious if there exists a JavaScript adaptation of a G ...

Can you explain the distinction between using `new ObjectId()`, `new ObjectId`, and `ObjectId()` in

Consider this initial definition in a file: const ObjectId = mongoose.Types.ObjectId; Which method should you choose and why? // 1 new ObjectId; // 2 new ObjectId(); // 3 ObjectId(); The official documentation recommends using new ObjectId. Person ...

Is there a way to verify the file extension in a multi-input form during an upload process?

I am looking for a solution that requests users to upload 4 different files when filling out the form. Check out this example of one of the inputs: <div class="custom-file"> <input type="file" class="custom-file-input" accept="video/*" id="v ...

Customize chrome's default shortcuts with JavaScript

I'm working on an application that requires me to override some shortcut keys in the Chrome browser. While I'm able to create custom shortcuts to trigger alerts like in this Stackblitz example, I'm having trouble overriding a few default sho ...

Step-by-step guide on visually comparing two iframes for differences

Scenario : In my project, I am dealing with 2 iframes that contain a significant number of divs and other controls, making both iframes similar in size to complete HTML websites. My goal is to compare these two iframes and identify any differences. Consi ...

eliminating items from an array nested inside another array

****************UPDATED********************************************************* I am stuck trying to manipulate an array within another array and remove elements based on conditions. The main goal is to make changes without altering the original array of ...

Setting up SSL/TLS certificates with Axios and Nest JS

I have a Nest JS application set up to send data from a local service to an online service. However, the requests are not working because we do not have an SSL certificate at the moment. Can anyone provide guidance on configuring Axios in Nest JS to accept ...

Utilize CamelCase in jQuery for Better Code Readability

Upon examining the jQuery source code, I noticed an interesting use of camelcase: camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); } // where: rmsPrefix = /^-ms-/, rdashAlpha = /-([\da- ...

Using both limit and sort functions simultaneously in YUI3 with YQL

Currently, I have a YQL query that successfully combines multiple RSS feeds and then sorts them by date. While this is effective, I am interested in implementing pagination to manage the results more efficiently. Below is the existing query I'm worki ...