Search code examples
typescriptvue.jsasync-awaitgrpcgrpc-web

How to use async/await pattern with gRPC Web?


I'm developing a Vue.js web application and I'm using gRPC to assure the communication.

In the frontend, I'm using the web version of gRPC: grpc-web.

Everything is working just fine; however, when I'm doing an API call in my store, e.g.:

async fetchEcho() {
    const echoService = new EchoServiceClient('http://localhost:8080', null, null);

    const request = new EchoRequest();
    request.setMessage('Hello World!');

    const call = echoService.echo(request, {'custom-header-1': 'value1'},
      (err: grpcWeb.Error, response: EchoResponse) => {
        console.log(response.getMessage());
    });
}

How can I use the async/await pattern when making the call in my Vue file, e.g.:

await fetchEcho();
// ...

And await until the API call has finished to resume my the course of my program?

Thanks!


Solution

  • I'm using ServicePromiseClient, the example would be something like this:

    const echoServiceClient = new EchoServicePromiseClient("http://localhost:8080", null, null);
    

    Then I'm able to create async functions for fetching like this:

    async function fetchEcho() {
        const echoReq = new EchoRequest();
        echoReq.setMessage("Hello world!");
        try {
            const response = await echoServiceClient.echo(echoReq, {});
            return response;
        } catch (error) {
            console.log(error);
            return null;
        }
    }