How to use async/await pattern with gRPC Web?
Asked Answered
G

2

7

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!

Gine answered 28/8, 2020 at 13:56 Comment(1)
await is used with promises. Is there a form of echo that returns a promise instead of calling a callback?Ehudd
R
5

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;
    }
}
Reword answered 29/8, 2020 at 5:9 Comment(2)
what's EchoServicePromiseClient (?) @RewordBareback
@MarlonLópez alternative (promise) client, based on this tutorial: github.com/grpc/grpc-web#3-write-your-js-clientReword
O
1

The *PromiseClinet seems not to be generated anymore. In lieu of that there is a method with a signature that returns a promise

 search(
    request: microservice_1_test_pb.SearchRequest,
    metadata: grpcWeb.Metadata | null): Promise<microservice_1_test_pb.SearchResponse>;

  search(
    request: microservice_1_test_pb.SearchRequest,
    metadata: grpcWeb.Metadata | null,
    callback: (err: grpcWeb.RpcError,
               response: microservice_1_test_pb.SearchResponse) => void): grpcWeb.ClientReadableStream<microservice_1_test_pb.SearchResponse>;

Using the first

    try {
      let response = await this.searchService.search(searchRequest, {})
      this.responseData.data = response.getSearchResponse()

    } catch (error) {
      console.log("Got error from server: grpcWeb.RpcError).message-->", (error as grpcWeb.RpcError).message)
      this.responseData.error = (error as grpcWeb.RpcError)

    }
Organza answered 30/8, 2022 at 13:1 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.