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

Bas*_*hen 7 async-await typescript vue.js grpc 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());
    });
}
Run Code Online (Sandbox Code Playgroud)

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

await fetchEcho();
// ...
Run Code Online (Sandbox Code Playgroud)

并等到 API 调用完成才能恢复我的程序进程?

谢谢!

小智 5

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

const echoServiceClient = new EchoServicePromiseClient("http://localhost:8080", null, null);
Run Code Online (Sandbox Code Playgroud)

然后我可以创建异步函数来进行提取,如下所示:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)