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, eg:
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, eg:
await fetchEcho();
// ...
And await until the API call has finished to resume my the course of my program?
Thanks!
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;
}
}
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)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.