如何在gRPC Web中使用异步/等待模式?

问题描述

我正在开发Vue.js Web应用程序,并且正在使用gRPC来确保通信。

在前端,我使用的是gRPC的网络版本:grpc-web

一切正常。但是,当我在商店中进行API调用时,例如:

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());
    });
}

在Vue文件中进行通话时,如何使用async/await模式,例如:

await fetchEcho();
// ...

等到API调用完成后,才能继续执行我的程序吗?

谢谢!

解决方法

我正在使用ServicePromiseClient,示例将如下所示:

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

然后,我可以创建异步函数来进行这样的提取:

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;
    }
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...